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 |
---|---|---|---|---|---|---|---|---|---|---|---|
andymeneely/squib | lib/squib/sample_helpers.rb | Squib.Deck.sample | def sample(str)
@sample_x ||= 100
@sample_y ||= 100
rect x: 460, y: @sample_y - 40, width: 600,
height: 180, fill_color: '#FFD655', stroke_color: 'black', radius: 15
text str: str, x: 460, y: @sample_y - 40,
width: 540, height: 180,
valign: 'middle', align: 'center',
font: 'Times New Roman,Serif 8'
yield @sample_x, @sample_y
@sample_y += 200
end | ruby | def sample(str)
@sample_x ||= 100
@sample_y ||= 100
rect x: 460, y: @sample_y - 40, width: 600,
height: 180, fill_color: '#FFD655', stroke_color: 'black', radius: 15
text str: str, x: 460, y: @sample_y - 40,
width: 540, height: 180,
valign: 'middle', align: 'center',
font: 'Times New Roman,Serif 8'
yield @sample_x, @sample_y
@sample_y += 200
end | [
"def",
"sample",
"(",
"str",
")",
"@sample_x",
"||=",
"100",
"@sample_y",
"||=",
"100",
"rect",
"x",
":",
"460",
",",
"y",
":",
"@sample_y",
"-",
"40",
",",
"width",
":",
"600",
",",
"height",
":",
"180",
",",
"fill_color",
":",
"'#FFD655'",
",",
"stroke_color",
":",
"'black'",
",",
"radius",
":",
"15",
"text",
"str",
":",
"str",
",",
"x",
":",
"460",
",",
"y",
":",
"@sample_y",
"-",
"40",
",",
"width",
":",
"540",
",",
"height",
":",
"180",
",",
"valign",
":",
"'middle'",
",",
"align",
":",
"'center'",
",",
"font",
":",
"'Times New Roman,Serif 8'",
"yield",
"@sample_x",
",",
"@sample_y",
"@sample_y",
"+=",
"200",
"end"
] | Define a set of samples on some graph paper | [
"Define",
"a",
"set",
"of",
"samples",
"on",
"some",
"graph",
"paper"
] | 1d307fe6e00306e7b21f35e6c51955724e4e0673 | https://github.com/andymeneely/squib/blob/1d307fe6e00306e7b21f35e6c51955724e4e0673/lib/squib/sample_helpers.rb#L19-L30 | train |
andymeneely/squib | lib/squib/api/groups.rb | Squib.Deck.enable_groups_from_env! | def enable_groups_from_env!
return if ENV['SQUIB_BUILD'].nil?
ENV['SQUIB_BUILD'].split(',').each do |grp|
enable_build grp.strip.to_sym
end
end | ruby | def enable_groups_from_env!
return if ENV['SQUIB_BUILD'].nil?
ENV['SQUIB_BUILD'].split(',').each do |grp|
enable_build grp.strip.to_sym
end
end | [
"def",
"enable_groups_from_env!",
"return",
"if",
"ENV",
"[",
"'SQUIB_BUILD'",
"]",
".",
"nil?",
"ENV",
"[",
"'SQUIB_BUILD'",
"]",
".",
"split",
"(",
"','",
")",
".",
"each",
"do",
"|",
"grp",
"|",
"enable_build",
"grp",
".",
"strip",
".",
"to_sym",
"end",
"end"
] | Not a DSL method, but initialized from Deck.new | [
"Not",
"a",
"DSL",
"method",
"but",
"initialized",
"from",
"Deck",
".",
"new"
] | 1d307fe6e00306e7b21f35e6c51955724e4e0673 | https://github.com/andymeneely/squib/blob/1d307fe6e00306e7b21f35e6c51955724e4e0673/lib/squib/api/groups.rb#L46-L51 | train |
andymeneely/squib | lib/squib/layout_parser.rb | Squib.LayoutParser.parents_exist? | def parents_exist?(yml, key)
exists = true
Array(yml[key]['extends']).each do |parent|
unless yml.key?(parent)
exists = false unless
Squib.logger.error "Processing layout: '#{key}' attempts to extend a missing '#{yml[key]['extends']}'"
end
end
return exists
end | ruby | def parents_exist?(yml, key)
exists = true
Array(yml[key]['extends']).each do |parent|
unless yml.key?(parent)
exists = false unless
Squib.logger.error "Processing layout: '#{key}' attempts to extend a missing '#{yml[key]['extends']}'"
end
end
return exists
end | [
"def",
"parents_exist?",
"(",
"yml",
",",
"key",
")",
"exists",
"=",
"true",
"Array",
"(",
"yml",
"[",
"key",
"]",
"[",
"'extends'",
"]",
")",
".",
"each",
"do",
"|",
"parent",
"|",
"unless",
"yml",
".",
"key?",
"(",
"parent",
")",
"exists",
"=",
"false",
"unless",
"Squib",
".",
"logger",
".",
"error",
"\"Processing layout: '#{key}' attempts to extend a missing '#{yml[key]['extends']}'\"",
"end",
"end",
"return",
"exists",
"end"
] | Checks if we have any absentee parents
@api private | [
"Checks",
"if",
"we",
"have",
"any",
"absentee",
"parents"
] | 1d307fe6e00306e7b21f35e6c51955724e4e0673 | https://github.com/andymeneely/squib/blob/1d307fe6e00306e7b21f35e6c51955724e4e0673/lib/squib/layout_parser.rb#L117-L126 | train |
andymeneely/squib | lib/squib/graphics/text.rb | Squib.Card.compute_carve | def compute_carve(rule, range)
w = rule[:box].width[@index]
if w == :native
file = rule[:file][@index].file
case rule[:type]
when :png
Squib.cache_load_image(file).width.to_f / (range.size - 1)
when :svg
svg_data = rule[:svg_args].data[@index]
unless file.to_s.empty? || svg_data.to_s.empty?
Squib.logger.warn 'Both an SVG file and SVG data were specified'
end
return 0 if (file.nil? or file.eql? '') and svg_data.nil?
svg_data = File.read(file) if svg_data.to_s.empty?
RSVG::Handle.new_from_data(svg_data).width
end
else
rule[:box].width[@index] * Pango::SCALE / (range.size - 1)
end
end | ruby | def compute_carve(rule, range)
w = rule[:box].width[@index]
if w == :native
file = rule[:file][@index].file
case rule[:type]
when :png
Squib.cache_load_image(file).width.to_f / (range.size - 1)
when :svg
svg_data = rule[:svg_args].data[@index]
unless file.to_s.empty? || svg_data.to_s.empty?
Squib.logger.warn 'Both an SVG file and SVG data were specified'
end
return 0 if (file.nil? or file.eql? '') and svg_data.nil?
svg_data = File.read(file) if svg_data.to_s.empty?
RSVG::Handle.new_from_data(svg_data).width
end
else
rule[:box].width[@index] * Pango::SCALE / (range.size - 1)
end
end | [
"def",
"compute_carve",
"(",
"rule",
",",
"range",
")",
"w",
"=",
"rule",
"[",
":box",
"]",
".",
"width",
"[",
"@index",
"]",
"if",
"w",
"==",
":native",
"file",
"=",
"rule",
"[",
":file",
"]",
"[",
"@index",
"]",
".",
"file",
"case",
"rule",
"[",
":type",
"]",
"when",
":png",
"Squib",
".",
"cache_load_image",
"(",
"file",
")",
".",
"width",
".",
"to_f",
"/",
"(",
"range",
".",
"size",
"-",
"1",
")",
"when",
":svg",
"svg_data",
"=",
"rule",
"[",
":svg_args",
"]",
".",
"data",
"[",
"@index",
"]",
"unless",
"file",
".",
"to_s",
".",
"empty?",
"||",
"svg_data",
".",
"to_s",
".",
"empty?",
"Squib",
".",
"logger",
".",
"warn",
"'Both an SVG file and SVG data were specified'",
"end",
"return",
"0",
"if",
"(",
"file",
".",
"nil?",
"or",
"file",
".",
"eql?",
"''",
")",
"and",
"svg_data",
".",
"nil?",
"svg_data",
"=",
"File",
".",
"read",
"(",
"file",
")",
"if",
"svg_data",
".",
"to_s",
".",
"empty?",
"RSVG",
"::",
"Handle",
".",
"new_from_data",
"(",
"svg_data",
")",
".",
"width",
"end",
"else",
"rule",
"[",
":box",
"]",
".",
"width",
"[",
"@index",
"]",
"*",
"Pango",
"::",
"SCALE",
"/",
"(",
"range",
".",
"size",
"-",
"1",
")",
"end",
"end"
] | Compute the width of the carve that we need | [
"Compute",
"the",
"width",
"of",
"the",
"carve",
"that",
"we",
"need"
] | 1d307fe6e00306e7b21f35e6c51955724e4e0673 | https://github.com/andymeneely/squib/blob/1d307fe6e00306e7b21f35e6c51955724e4e0673/lib/squib/graphics/text.rb#L56-L75 | train |
andymeneely/squib | lib/squib/graphics/hand.rb | Squib.Deck.render_hand | def render_hand(range, sheet, hand)
cards = range.collect { |i| @cards[i] }
center_x = width / 2.0
center_y = hand.radius + height
out_size = 3.0 * center_y
angle_delta = (hand.angle_range.last - hand.angle_range.first) / cards.size
cxt = Cairo::Context.new(Cairo::RecordingSurface.new(0, 0, out_size, out_size))
cxt.translate(out_size / 2.0, out_size / 2.0)
cxt.rotate(hand.angle_range.first)
cxt.translate(-width, -width)
cards.each_with_index do |card, i|
cxt.translate(center_x, center_y)
cxt.rotate(angle_delta)
cxt.translate(-center_x, -center_y)
card.use_cairo do |card_cxt|
cxt.rounded_rectangle(sheet.trim, sheet.trim,
width - (2 * sheet.trim), height - (2 * sheet.trim),
sheet.trim_radius, sheet.trim_radius)
cxt.clip
cxt.set_source(card_cxt.target)
cxt.paint
cxt.reset_clip
end
end
x, y, w, h = cxt.target.ink_extents # I love Ruby assignment ;)
png_cxt = Squib::Graphics::CairoContextWrapper.new(Cairo::Context.new(Cairo::ImageSurface.new(w + 2 * sheet.margin, h + 2 * sheet.margin)))
png_cxt.set_source_squibcolor(sheet.fill_color)
png_cxt.paint
png_cxt.translate(-x + sheet.margin, -y + sheet.margin)
png_cxt.set_source(cxt.target)
png_cxt.paint
png_cxt.target.write_to_png sheet.full_filename
end | ruby | def render_hand(range, sheet, hand)
cards = range.collect { |i| @cards[i] }
center_x = width / 2.0
center_y = hand.radius + height
out_size = 3.0 * center_y
angle_delta = (hand.angle_range.last - hand.angle_range.first) / cards.size
cxt = Cairo::Context.new(Cairo::RecordingSurface.new(0, 0, out_size, out_size))
cxt.translate(out_size / 2.0, out_size / 2.0)
cxt.rotate(hand.angle_range.first)
cxt.translate(-width, -width)
cards.each_with_index do |card, i|
cxt.translate(center_x, center_y)
cxt.rotate(angle_delta)
cxt.translate(-center_x, -center_y)
card.use_cairo do |card_cxt|
cxt.rounded_rectangle(sheet.trim, sheet.trim,
width - (2 * sheet.trim), height - (2 * sheet.trim),
sheet.trim_radius, sheet.trim_radius)
cxt.clip
cxt.set_source(card_cxt.target)
cxt.paint
cxt.reset_clip
end
end
x, y, w, h = cxt.target.ink_extents # I love Ruby assignment ;)
png_cxt = Squib::Graphics::CairoContextWrapper.new(Cairo::Context.new(Cairo::ImageSurface.new(w + 2 * sheet.margin, h + 2 * sheet.margin)))
png_cxt.set_source_squibcolor(sheet.fill_color)
png_cxt.paint
png_cxt.translate(-x + sheet.margin, -y + sheet.margin)
png_cxt.set_source(cxt.target)
png_cxt.paint
png_cxt.target.write_to_png sheet.full_filename
end | [
"def",
"render_hand",
"(",
"range",
",",
"sheet",
",",
"hand",
")",
"cards",
"=",
"range",
".",
"collect",
"{",
"|",
"i",
"|",
"@cards",
"[",
"i",
"]",
"}",
"center_x",
"=",
"width",
"/",
"2.0",
"center_y",
"=",
"hand",
".",
"radius",
"+",
"height",
"out_size",
"=",
"3.0",
"*",
"center_y",
"angle_delta",
"=",
"(",
"hand",
".",
"angle_range",
".",
"last",
"-",
"hand",
".",
"angle_range",
".",
"first",
")",
"/",
"cards",
".",
"size",
"cxt",
"=",
"Cairo",
"::",
"Context",
".",
"new",
"(",
"Cairo",
"::",
"RecordingSurface",
".",
"new",
"(",
"0",
",",
"0",
",",
"out_size",
",",
"out_size",
")",
")",
"cxt",
".",
"translate",
"(",
"out_size",
"/",
"2.0",
",",
"out_size",
"/",
"2.0",
")",
"cxt",
".",
"rotate",
"(",
"hand",
".",
"angle_range",
".",
"first",
")",
"cxt",
".",
"translate",
"(",
"-",
"width",
",",
"-",
"width",
")",
"cards",
".",
"each_with_index",
"do",
"|",
"card",
",",
"i",
"|",
"cxt",
".",
"translate",
"(",
"center_x",
",",
"center_y",
")",
"cxt",
".",
"rotate",
"(",
"angle_delta",
")",
"cxt",
".",
"translate",
"(",
"-",
"center_x",
",",
"-",
"center_y",
")",
"card",
".",
"use_cairo",
"do",
"|",
"card_cxt",
"|",
"cxt",
".",
"rounded_rectangle",
"(",
"sheet",
".",
"trim",
",",
"sheet",
".",
"trim",
",",
"width",
"-",
"(",
"2",
"*",
"sheet",
".",
"trim",
")",
",",
"height",
"-",
"(",
"2",
"*",
"sheet",
".",
"trim",
")",
",",
"sheet",
".",
"trim_radius",
",",
"sheet",
".",
"trim_radius",
")",
"cxt",
".",
"clip",
"cxt",
".",
"set_source",
"(",
"card_cxt",
".",
"target",
")",
"cxt",
".",
"paint",
"cxt",
".",
"reset_clip",
"end",
"end",
"x",
",",
"y",
",",
"w",
",",
"h",
"=",
"cxt",
".",
"target",
".",
"ink_extents",
"# I love Ruby assignment ;)",
"png_cxt",
"=",
"Squib",
"::",
"Graphics",
"::",
"CairoContextWrapper",
".",
"new",
"(",
"Cairo",
"::",
"Context",
".",
"new",
"(",
"Cairo",
"::",
"ImageSurface",
".",
"new",
"(",
"w",
"+",
"2",
"*",
"sheet",
".",
"margin",
",",
"h",
"+",
"2",
"*",
"sheet",
".",
"margin",
")",
")",
")",
"png_cxt",
".",
"set_source_squibcolor",
"(",
"sheet",
".",
"fill_color",
")",
"png_cxt",
".",
"paint",
"png_cxt",
".",
"translate",
"(",
"-",
"x",
"+",
"sheet",
".",
"margin",
",",
"-",
"y",
"+",
"sheet",
".",
"margin",
")",
"png_cxt",
".",
"set_source",
"(",
"cxt",
".",
"target",
")",
"png_cxt",
".",
"paint",
"png_cxt",
".",
"target",
".",
"write_to_png",
"sheet",
".",
"full_filename",
"end"
] | Draw cards in a fan.
@api private | [
"Draw",
"cards",
"in",
"a",
"fan",
"."
] | 1d307fe6e00306e7b21f35e6c51955724e4e0673 | https://github.com/andymeneely/squib/blob/1d307fe6e00306e7b21f35e6c51955724e4e0673/lib/squib/graphics/hand.rb#L8-L40 | train |
andymeneely/squib | lib/squib/sprues/sprue.rb | Squib.Sprue.parse_crop_line | def parse_crop_line(line)
new_line = @crop_line_default.merge line
new_line['width'] = Args::UnitConversion.parse(new_line['width'], @dpi)
new_line['color'] = colorify new_line['color']
new_line['style_desc'] = new_line['style']
new_line['style'] = Sprues::CropLineDash.new(new_line['style'], @dpi)
new_line['line'] = Sprues::CropLine.new(
new_line['type'], new_line['position'], sheet_width, sheet_height, @dpi
)
new_line
end | ruby | def parse_crop_line(line)
new_line = @crop_line_default.merge line
new_line['width'] = Args::UnitConversion.parse(new_line['width'], @dpi)
new_line['color'] = colorify new_line['color']
new_line['style_desc'] = new_line['style']
new_line['style'] = Sprues::CropLineDash.new(new_line['style'], @dpi)
new_line['line'] = Sprues::CropLine.new(
new_line['type'], new_line['position'], sheet_width, sheet_height, @dpi
)
new_line
end | [
"def",
"parse_crop_line",
"(",
"line",
")",
"new_line",
"=",
"@crop_line_default",
".",
"merge",
"line",
"new_line",
"[",
"'width'",
"]",
"=",
"Args",
"::",
"UnitConversion",
".",
"parse",
"(",
"new_line",
"[",
"'width'",
"]",
",",
"@dpi",
")",
"new_line",
"[",
"'color'",
"]",
"=",
"colorify",
"new_line",
"[",
"'color'",
"]",
"new_line",
"[",
"'style_desc'",
"]",
"=",
"new_line",
"[",
"'style'",
"]",
"new_line",
"[",
"'style'",
"]",
"=",
"Sprues",
"::",
"CropLineDash",
".",
"new",
"(",
"new_line",
"[",
"'style'",
"]",
",",
"@dpi",
")",
"new_line",
"[",
"'line'",
"]",
"=",
"Sprues",
"::",
"CropLine",
".",
"new",
"(",
"new_line",
"[",
"'type'",
"]",
",",
"new_line",
"[",
"'position'",
"]",
",",
"sheet_width",
",",
"sheet_height",
",",
"@dpi",
")",
"new_line",
"end"
] | Parse crop line definitions from template. | [
"Parse",
"crop",
"line",
"definitions",
"from",
"template",
"."
] | 1d307fe6e00306e7b21f35e6c51955724e4e0673 | https://github.com/andymeneely/squib/blob/1d307fe6e00306e7b21f35e6c51955724e4e0673/lib/squib/sprues/sprue.rb#L150-L160 | train |
andymeneely/squib | lib/squib/sprues/sprue.rb | Squib.Sprue.parse_card | def parse_card(card)
new_card = card.clone
x = Args::UnitConversion.parse(card['x'], @dpi)
y = Args::UnitConversion.parse(card['y'], @dpi)
if @template_hash['position_reference'] == :center
# Normalize it to a top-left positional reference
x -= card_width / 2
y -= card_height / 2
end
new_card['x'] = x
new_card['y'] = y
new_card['rotate'] = parse_rotate_param(
card['rotate'] ? card['rotate'] : @template_hash['rotate'])
new_card
end | ruby | def parse_card(card)
new_card = card.clone
x = Args::UnitConversion.parse(card['x'], @dpi)
y = Args::UnitConversion.parse(card['y'], @dpi)
if @template_hash['position_reference'] == :center
# Normalize it to a top-left positional reference
x -= card_width / 2
y -= card_height / 2
end
new_card['x'] = x
new_card['y'] = y
new_card['rotate'] = parse_rotate_param(
card['rotate'] ? card['rotate'] : @template_hash['rotate'])
new_card
end | [
"def",
"parse_card",
"(",
"card",
")",
"new_card",
"=",
"card",
".",
"clone",
"x",
"=",
"Args",
"::",
"UnitConversion",
".",
"parse",
"(",
"card",
"[",
"'x'",
"]",
",",
"@dpi",
")",
"y",
"=",
"Args",
"::",
"UnitConversion",
".",
"parse",
"(",
"card",
"[",
"'y'",
"]",
",",
"@dpi",
")",
"if",
"@template_hash",
"[",
"'position_reference'",
"]",
"==",
":center",
"# Normalize it to a top-left positional reference",
"x",
"-=",
"card_width",
"/",
"2",
"y",
"-=",
"card_height",
"/",
"2",
"end",
"new_card",
"[",
"'x'",
"]",
"=",
"x",
"new_card",
"[",
"'y'",
"]",
"=",
"y",
"new_card",
"[",
"'rotate'",
"]",
"=",
"parse_rotate_param",
"(",
"card",
"[",
"'rotate'",
"]",
"?",
"card",
"[",
"'rotate'",
"]",
":",
"@template_hash",
"[",
"'rotate'",
"]",
")",
"new_card",
"end"
] | Parse card definitions from template. | [
"Parse",
"card",
"definitions",
"from",
"template",
"."
] | 1d307fe6e00306e7b21f35e6c51955724e4e0673 | https://github.com/andymeneely/squib/blob/1d307fe6e00306e7b21f35e6c51955724e4e0673/lib/squib/sprues/sprue.rb#L163-L179 | train |
westonganger/paper_trail-association_tracking | lib/paper_trail_association_tracking/record_trail.rb | PaperTrailAssociationTracking.RecordTrail.save_habtm_associations | def save_habtm_associations(version)
@record.class.reflect_on_all_associations(:has_and_belongs_to_many).each do |a|
next unless save_habtm_association?(a)
habtm_assoc_ids(a).each do |id|
::PaperTrail::VersionAssociation.create(
version_id: version.transaction_id,
foreign_key_name: a.name,
foreign_key_id: id,
foreign_type: a.klass
)
end
end
end | ruby | def save_habtm_associations(version)
@record.class.reflect_on_all_associations(:has_and_belongs_to_many).each do |a|
next unless save_habtm_association?(a)
habtm_assoc_ids(a).each do |id|
::PaperTrail::VersionAssociation.create(
version_id: version.transaction_id,
foreign_key_name: a.name,
foreign_key_id: id,
foreign_type: a.klass
)
end
end
end | [
"def",
"save_habtm_associations",
"(",
"version",
")",
"@record",
".",
"class",
".",
"reflect_on_all_associations",
"(",
":has_and_belongs_to_many",
")",
".",
"each",
"do",
"|",
"a",
"|",
"next",
"unless",
"save_habtm_association?",
"(",
"a",
")",
"habtm_assoc_ids",
"(",
"a",
")",
".",
"each",
"do",
"|",
"id",
"|",
"::",
"PaperTrail",
"::",
"VersionAssociation",
".",
"create",
"(",
"version_id",
":",
"version",
".",
"transaction_id",
",",
"foreign_key_name",
":",
"a",
".",
"name",
",",
"foreign_key_id",
":",
"id",
",",
"foreign_type",
":",
"a",
".",
"klass",
")",
"end",
"end",
"end"
] | When a record is created, updated, or destroyed, we determine what the
HABTM associations looked like before any changes were made, by using
the `paper_trail_habtm` data structure. Then, we create
`VersionAssociation` records for each of the associated records.
@api private | [
"When",
"a",
"record",
"is",
"created",
"updated",
"or",
"destroyed",
"we",
"determine",
"what",
"the",
"HABTM",
"associations",
"looked",
"like",
"before",
"any",
"changes",
"were",
"made",
"by",
"using",
"the",
"paper_trail_habtm",
"data",
"structure",
".",
"Then",
"we",
"create",
"VersionAssociation",
"records",
"for",
"each",
"of",
"the",
"associated",
"records",
"."
] | cfda3e0642323e78cf28196d22bd4c9533398b41 | https://github.com/westonganger/paper_trail-association_tracking/blob/cfda3e0642323e78cf28196d22bd4c9533398b41/lib/paper_trail_association_tracking/record_trail.rb#L132-L144 | train |
westonganger/paper_trail-association_tracking | lib/paper_trail_association_tracking/record_trail.rb | PaperTrailAssociationTracking.RecordTrail.habtm_assoc_ids | def habtm_assoc_ids(habtm_assoc)
current = @record.send(habtm_assoc.name).to_a.map(&:id) # TODO: `pluck` would use less memory
removed = @record.paper_trail_habtm.try(:[], habtm_assoc.name).try(:[], :removed) || []
added = @record.paper_trail_habtm.try(:[], habtm_assoc.name).try(:[], :added) || []
current + removed - added
end | ruby | def habtm_assoc_ids(habtm_assoc)
current = @record.send(habtm_assoc.name).to_a.map(&:id) # TODO: `pluck` would use less memory
removed = @record.paper_trail_habtm.try(:[], habtm_assoc.name).try(:[], :removed) || []
added = @record.paper_trail_habtm.try(:[], habtm_assoc.name).try(:[], :added) || []
current + removed - added
end | [
"def",
"habtm_assoc_ids",
"(",
"habtm_assoc",
")",
"current",
"=",
"@record",
".",
"send",
"(",
"habtm_assoc",
".",
"name",
")",
".",
"to_a",
".",
"map",
"(",
":id",
")",
"# TODO: `pluck` would use less memory",
"removed",
"=",
"@record",
".",
"paper_trail_habtm",
".",
"try",
"(",
":[]",
",",
"habtm_assoc",
".",
"name",
")",
".",
"try",
"(",
":[]",
",",
":removed",
")",
"||",
"[",
"]",
"added",
"=",
"@record",
".",
"paper_trail_habtm",
".",
"try",
"(",
":[]",
",",
"habtm_assoc",
".",
"name",
")",
".",
"try",
"(",
":[]",
",",
":added",
")",
"||",
"[",
"]",
"current",
"+",
"removed",
"-",
"added",
"end"
] | Given a HABTM association, returns an array of ids.
@api private | [
"Given",
"a",
"HABTM",
"association",
"returns",
"an",
"array",
"of",
"ids",
"."
] | cfda3e0642323e78cf28196d22bd4c9533398b41 | https://github.com/westonganger/paper_trail-association_tracking/blob/cfda3e0642323e78cf28196d22bd4c9533398b41/lib/paper_trail_association_tracking/record_trail.rb#L156-L161 | train |
westonganger/paper_trail-association_tracking | lib/paper_trail_association_tracking/record_trail.rb | PaperTrailAssociationTracking.RecordTrail.save_bt_association | def save_bt_association(assoc, version)
assoc_version_args = {
version_id: version.id,
foreign_key_name: assoc.foreign_key
}
if assoc.options[:polymorphic]
foreign_type = @record.send(assoc.foreign_type)
if foreign_type && ::PaperTrail.request.enabled_for_model?(foreign_type.constantize)
assoc_version_args[:foreign_key_id] = @record.send(assoc.foreign_key)
assoc_version_args[:foreign_type] = foreign_type
end
elsif ::PaperTrail.request.enabled_for_model?(assoc.klass)
assoc_version_args[:foreign_key_id] = @record.send(assoc.foreign_key)
assoc_version_args[:foreign_type] = assoc.klass
end
if assoc_version_args.key?(:foreign_key_id)
::PaperTrail::VersionAssociation.create(assoc_version_args)
end
end | ruby | def save_bt_association(assoc, version)
assoc_version_args = {
version_id: version.id,
foreign_key_name: assoc.foreign_key
}
if assoc.options[:polymorphic]
foreign_type = @record.send(assoc.foreign_type)
if foreign_type && ::PaperTrail.request.enabled_for_model?(foreign_type.constantize)
assoc_version_args[:foreign_key_id] = @record.send(assoc.foreign_key)
assoc_version_args[:foreign_type] = foreign_type
end
elsif ::PaperTrail.request.enabled_for_model?(assoc.klass)
assoc_version_args[:foreign_key_id] = @record.send(assoc.foreign_key)
assoc_version_args[:foreign_type] = assoc.klass
end
if assoc_version_args.key?(:foreign_key_id)
::PaperTrail::VersionAssociation.create(assoc_version_args)
end
end | [
"def",
"save_bt_association",
"(",
"assoc",
",",
"version",
")",
"assoc_version_args",
"=",
"{",
"version_id",
":",
"version",
".",
"id",
",",
"foreign_key_name",
":",
"assoc",
".",
"foreign_key",
"}",
"if",
"assoc",
".",
"options",
"[",
":polymorphic",
"]",
"foreign_type",
"=",
"@record",
".",
"send",
"(",
"assoc",
".",
"foreign_type",
")",
"if",
"foreign_type",
"&&",
"::",
"PaperTrail",
".",
"request",
".",
"enabled_for_model?",
"(",
"foreign_type",
".",
"constantize",
")",
"assoc_version_args",
"[",
":foreign_key_id",
"]",
"=",
"@record",
".",
"send",
"(",
"assoc",
".",
"foreign_key",
")",
"assoc_version_args",
"[",
":foreign_type",
"]",
"=",
"foreign_type",
"end",
"elsif",
"::",
"PaperTrail",
".",
"request",
".",
"enabled_for_model?",
"(",
"assoc",
".",
"klass",
")",
"assoc_version_args",
"[",
":foreign_key_id",
"]",
"=",
"@record",
".",
"send",
"(",
"assoc",
".",
"foreign_key",
")",
"assoc_version_args",
"[",
":foreign_type",
"]",
"=",
"assoc",
".",
"klass",
"end",
"if",
"assoc_version_args",
".",
"key?",
"(",
":foreign_key_id",
")",
"::",
"PaperTrail",
"::",
"VersionAssociation",
".",
"create",
"(",
"assoc_version_args",
")",
"end",
"end"
] | Save a single `belongs_to` association.
@api private | [
"Save",
"a",
"single",
"belongs_to",
"association",
"."
] | cfda3e0642323e78cf28196d22bd4c9533398b41 | https://github.com/westonganger/paper_trail-association_tracking/blob/cfda3e0642323e78cf28196d22bd4c9533398b41/lib/paper_trail_association_tracking/record_trail.rb#L165-L185 | train |
westonganger/paper_trail-association_tracking | lib/paper_trail_association_tracking/record_trail.rb | PaperTrailAssociationTracking.RecordTrail.save_habtm_association? | def save_habtm_association?(assoc)
@record.class.paper_trail_save_join_tables.include?(assoc.name) ||
::PaperTrail.request.enabled_for_model?(assoc.klass)
end | ruby | def save_habtm_association?(assoc)
@record.class.paper_trail_save_join_tables.include?(assoc.name) ||
::PaperTrail.request.enabled_for_model?(assoc.klass)
end | [
"def",
"save_habtm_association?",
"(",
"assoc",
")",
"@record",
".",
"class",
".",
"paper_trail_save_join_tables",
".",
"include?",
"(",
"assoc",
".",
"name",
")",
"||",
"::",
"PaperTrail",
".",
"request",
".",
"enabled_for_model?",
"(",
"assoc",
".",
"klass",
")",
"end"
] | Returns true if the given HABTM association should be saved.
@api private | [
"Returns",
"true",
"if",
"the",
"given",
"HABTM",
"association",
"should",
"be",
"saved",
"."
] | cfda3e0642323e78cf28196d22bd4c9533398b41 | https://github.com/westonganger/paper_trail-association_tracking/blob/cfda3e0642323e78cf28196d22bd4c9533398b41/lib/paper_trail_association_tracking/record_trail.rb#L189-L192 | train |
westonganger/paper_trail-association_tracking | lib/paper_trail_association_tracking/model_config.rb | PaperTrailAssociationTracking.ModelConfig.assert_concrete_activerecord_class | def assert_concrete_activerecord_class(class_name)
if class_name.constantize.abstract_class?
raise format(::PaperTrail::ModelConfig::E_HPT_ABSTRACT_CLASS, @model_class, class_name)
end
end | ruby | def assert_concrete_activerecord_class(class_name)
if class_name.constantize.abstract_class?
raise format(::PaperTrail::ModelConfig::E_HPT_ABSTRACT_CLASS, @model_class, class_name)
end
end | [
"def",
"assert_concrete_activerecord_class",
"(",
"class_name",
")",
"if",
"class_name",
".",
"constantize",
".",
"abstract_class?",
"raise",
"format",
"(",
"::",
"PaperTrail",
"::",
"ModelConfig",
"::",
"E_HPT_ABSTRACT_CLASS",
",",
"@model_class",
",",
"class_name",
")",
"end",
"end"
] | Raises an error if the provided class is an `abstract_class`.
@api private | [
"Raises",
"an",
"error",
"if",
"the",
"provided",
"class",
"is",
"an",
"abstract_class",
"."
] | cfda3e0642323e78cf28196d22bd4c9533398b41 | https://github.com/westonganger/paper_trail-association_tracking/blob/cfda3e0642323e78cf28196d22bd4c9533398b41/lib/paper_trail_association_tracking/model_config.rb#L21-L25 | train |
chef/chef-provisioning-aws | lib/chef/provisioning/aws_driver/aws_provider.rb | Chef::Provisioning::AWSDriver.AWSProvider.wait_for | def wait_for(opts = {})
aws_object = opts[:aws_object]
query_method = opts[:query_method]
expected_responses = [opts[:expected_responses]].flatten
acceptable_errors = [opts[:acceptable_errors] || []].flatten
tries = opts[:tries] || 60
sleep = opts[:sleep] || 5
Retryable.retryable(tries: tries, sleep: sleep) do |retries, exception|
action_handler.report_progress "waited #{retries * sleep}/#{tries * sleep}s for <#{aws_object.class}:#{aws_object.id}>##{query_method} state to change to #{expected_responses.inspect}..."
Chef::Log.debug("Current exception in wait_for is #{exception.inspect}") if exception
begin
yield(aws_object) if block_given?
if aws_object.class.to_s.eql?("Aws::EC2::Vpc")
vpc = new_resource.driver.ec2.describe_vpcs(vpc_ids: [aws_object.vpc_id]).vpcs
current_response = "[:#{vpc[0].state}]"
elsif aws_object.class.to_s.eql?("Aws::EC2::NetworkInterface")
result = new_resource.driver.ec2_resource.network_interface(aws_object.id)
current_response = "[:#{result.status}]"
current_response = "[:in_use]" if current_response.eql?("[:in-use]")
elsif aws_object.class.to_s.eql?("Aws::EC2::NatGateway")
current_response = "[:#{aws_object.state}]"
end
Chef::Log.debug("Current response in wait_for from [#{query_method}] is #{current_response}")
unless expected_responses.to_s.include?(current_response)
raise StatusTimeoutError.new(aws_object, current_response, expected_responses)
end
rescue *acceptable_errors
end
end
end | ruby | def wait_for(opts = {})
aws_object = opts[:aws_object]
query_method = opts[:query_method]
expected_responses = [opts[:expected_responses]].flatten
acceptable_errors = [opts[:acceptable_errors] || []].flatten
tries = opts[:tries] || 60
sleep = opts[:sleep] || 5
Retryable.retryable(tries: tries, sleep: sleep) do |retries, exception|
action_handler.report_progress "waited #{retries * sleep}/#{tries * sleep}s for <#{aws_object.class}:#{aws_object.id}>##{query_method} state to change to #{expected_responses.inspect}..."
Chef::Log.debug("Current exception in wait_for is #{exception.inspect}") if exception
begin
yield(aws_object) if block_given?
if aws_object.class.to_s.eql?("Aws::EC2::Vpc")
vpc = new_resource.driver.ec2.describe_vpcs(vpc_ids: [aws_object.vpc_id]).vpcs
current_response = "[:#{vpc[0].state}]"
elsif aws_object.class.to_s.eql?("Aws::EC2::NetworkInterface")
result = new_resource.driver.ec2_resource.network_interface(aws_object.id)
current_response = "[:#{result.status}]"
current_response = "[:in_use]" if current_response.eql?("[:in-use]")
elsif aws_object.class.to_s.eql?("Aws::EC2::NatGateway")
current_response = "[:#{aws_object.state}]"
end
Chef::Log.debug("Current response in wait_for from [#{query_method}] is #{current_response}")
unless expected_responses.to_s.include?(current_response)
raise StatusTimeoutError.new(aws_object, current_response, expected_responses)
end
rescue *acceptable_errors
end
end
end | [
"def",
"wait_for",
"(",
"opts",
"=",
"{",
"}",
")",
"aws_object",
"=",
"opts",
"[",
":aws_object",
"]",
"query_method",
"=",
"opts",
"[",
":query_method",
"]",
"expected_responses",
"=",
"[",
"opts",
"[",
":expected_responses",
"]",
"]",
".",
"flatten",
"acceptable_errors",
"=",
"[",
"opts",
"[",
":acceptable_errors",
"]",
"||",
"[",
"]",
"]",
".",
"flatten",
"tries",
"=",
"opts",
"[",
":tries",
"]",
"||",
"60",
"sleep",
"=",
"opts",
"[",
":sleep",
"]",
"||",
"5",
"Retryable",
".",
"retryable",
"(",
"tries",
":",
"tries",
",",
"sleep",
":",
"sleep",
")",
"do",
"|",
"retries",
",",
"exception",
"|",
"action_handler",
".",
"report_progress",
"\"waited #{retries * sleep}/#{tries * sleep}s for <#{aws_object.class}:#{aws_object.id}>##{query_method} state to change to #{expected_responses.inspect}...\"",
"Chef",
"::",
"Log",
".",
"debug",
"(",
"\"Current exception in wait_for is #{exception.inspect}\"",
")",
"if",
"exception",
"begin",
"yield",
"(",
"aws_object",
")",
"if",
"block_given?",
"if",
"aws_object",
".",
"class",
".",
"to_s",
".",
"eql?",
"(",
"\"Aws::EC2::Vpc\"",
")",
"vpc",
"=",
"new_resource",
".",
"driver",
".",
"ec2",
".",
"describe_vpcs",
"(",
"vpc_ids",
":",
"[",
"aws_object",
".",
"vpc_id",
"]",
")",
".",
"vpcs",
"current_response",
"=",
"\"[:#{vpc[0].state}]\"",
"elsif",
"aws_object",
".",
"class",
".",
"to_s",
".",
"eql?",
"(",
"\"Aws::EC2::NetworkInterface\"",
")",
"result",
"=",
"new_resource",
".",
"driver",
".",
"ec2_resource",
".",
"network_interface",
"(",
"aws_object",
".",
"id",
")",
"current_response",
"=",
"\"[:#{result.status}]\"",
"current_response",
"=",
"\"[:in_use]\"",
"if",
"current_response",
".",
"eql?",
"(",
"\"[:in-use]\"",
")",
"elsif",
"aws_object",
".",
"class",
".",
"to_s",
".",
"eql?",
"(",
"\"Aws::EC2::NatGateway\"",
")",
"current_response",
"=",
"\"[:#{aws_object.state}]\"",
"end",
"Chef",
"::",
"Log",
".",
"debug",
"(",
"\"Current response in wait_for from [#{query_method}] is #{current_response}\"",
")",
"unless",
"expected_responses",
".",
"to_s",
".",
"include?",
"(",
"current_response",
")",
"raise",
"StatusTimeoutError",
".",
"new",
"(",
"aws_object",
",",
"current_response",
",",
"expected_responses",
")",
"end",
"rescue",
"acceptable_errors",
"end",
"end",
"end"
] | Wait until aws_object obtains one of expected_responses
@param aws_object Aws SDK Object to check state on
@param query_method Method to call on aws_object to get current state
@param expected_responses [Symbol,Array<Symbol>] Final state(s) to look for
@param acceptable_errors [Exception,Array<Exception>] Acceptable errors that are caught and squelched
@param tries [Integer] Number of times to check state, defaults to 60
@param sleep [Integer] Time to wait between checking states, defaults to 5 | [
"Wait",
"until",
"aws_object",
"obtains",
"one",
"of",
"expected_responses"
] | 1ee70af5c4a9c23d028218736df089bbe5ec3c08 | https://github.com/chef/chef-provisioning-aws/blob/1ee70af5c4a9c23d028218736df089bbe5ec3c08/lib/chef/provisioning/aws_driver/aws_provider.rb#L257-L287 | train |
chicks/aes | lib/aes/aes.rb | AES.AES._random_seed | def _random_seed(size=32)
if defined? OpenSSL::Random
return OpenSSL::Random.random_bytes(size)
else
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
(1..size).collect{|a| chars[rand(chars.size)] }.join
end
end | ruby | def _random_seed(size=32)
if defined? OpenSSL::Random
return OpenSSL::Random.random_bytes(size)
else
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
(1..size).collect{|a| chars[rand(chars.size)] }.join
end
end | [
"def",
"_random_seed",
"(",
"size",
"=",
"32",
")",
"if",
"defined?",
"OpenSSL",
"::",
"Random",
"return",
"OpenSSL",
"::",
"Random",
".",
"random_bytes",
"(",
"size",
")",
"else",
"chars",
"=",
"(",
"\"a\"",
"..",
"\"z\"",
")",
".",
"to_a",
"+",
"(",
"\"A\"",
"..",
"\"Z\"",
")",
".",
"to_a",
"+",
"(",
"\"0\"",
"..",
"\"9\"",
")",
".",
"to_a",
"(",
"1",
"..",
"size",
")",
".",
"collect",
"{",
"|",
"a",
"|",
"chars",
"[",
"rand",
"(",
"chars",
".",
"size",
")",
"]",
"}",
".",
"join",
"end",
"end"
] | Generates a random seed value | [
"Generates",
"a",
"random",
"seed",
"value"
] | 001f77806a2cbef513315993e19a8f679f8f5786 | https://github.com/chicks/aes/blob/001f77806a2cbef513315993e19a8f679f8f5786/lib/aes/aes.rb#L93-L100 | train |
chicks/aes | lib/aes/aes.rb | AES.AES.b64_d | def b64_d(data)
iv_and_ctext = []
data.split('$').each do |part|
iv_and_ctext << Base64.decode64(part)
end
iv_and_ctext
end | ruby | def b64_d(data)
iv_and_ctext = []
data.split('$').each do |part|
iv_and_ctext << Base64.decode64(part)
end
iv_and_ctext
end | [
"def",
"b64_d",
"(",
"data",
")",
"iv_and_ctext",
"=",
"[",
"]",
"data",
".",
"split",
"(",
"'$'",
")",
".",
"each",
"do",
"|",
"part",
"|",
"iv_and_ctext",
"<<",
"Base64",
".",
"decode64",
"(",
"part",
")",
"end",
"iv_and_ctext",
"end"
] | Un-Base64's the IV and CipherText
Returns an array containing the IV, and CipherText | [
"Un",
"-",
"Base64",
"s",
"the",
"IV",
"and",
"CipherText",
"Returns",
"an",
"array",
"containing",
"the",
"IV",
"and",
"CipherText"
] | 001f77806a2cbef513315993e19a8f679f8f5786 | https://github.com/chicks/aes/blob/001f77806a2cbef513315993e19a8f679f8f5786/lib/aes/aes.rb#L104-L110 | train |
chicks/aes | lib/aes/aes.rb | AES.AES._setup | def _setup(action)
@cipher ||= OpenSSL::Cipher.new(@options[:cipher])
# Toggles encryption mode
@cipher.send(action)
@cipher.padding = @options[:padding]
@cipher.key = @key.unpack('a2'*32).map{|x| x.hex}.pack('c'*32)
end | ruby | def _setup(action)
@cipher ||= OpenSSL::Cipher.new(@options[:cipher])
# Toggles encryption mode
@cipher.send(action)
@cipher.padding = @options[:padding]
@cipher.key = @key.unpack('a2'*32).map{|x| x.hex}.pack('c'*32)
end | [
"def",
"_setup",
"(",
"action",
")",
"@cipher",
"||=",
"OpenSSL",
"::",
"Cipher",
".",
"new",
"(",
"@options",
"[",
":cipher",
"]",
")",
"# Toggles encryption mode",
"@cipher",
".",
"send",
"(",
"action",
")",
"@cipher",
".",
"padding",
"=",
"@options",
"[",
":padding",
"]",
"@cipher",
".",
"key",
"=",
"@key",
".",
"unpack",
"(",
"'a2'",
"*",
"32",
")",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"hex",
"}",
".",
"pack",
"(",
"'c'",
"*",
"32",
")",
"end"
] | Create a new cipher using the cipher type specified | [
"Create",
"a",
"new",
"cipher",
"using",
"the",
"cipher",
"type",
"specified"
] | 001f77806a2cbef513315993e19a8f679f8f5786 | https://github.com/chicks/aes/blob/001f77806a2cbef513315993e19a8f679f8f5786/lib/aes/aes.rb#L150-L156 | train |
radiant/radiant | lib/radiant/engine.rb | Radiant.Engine.default_load_paths | def default_load_paths
paths = ["#{RADIANT_ROOT}/test/mocks/#{environment}"]
# Add the app's controller directory
paths.concat(Dir["#{RADIANT_ROOT}/app/controllers/"])
# Followed by the standard includes.
paths.concat %w(
app
app/metal
app/models
app/controllers
app/helpers
config
lib
vendor
).map { |dir| "#{RADIANT_ROOT}/#{dir}" }.select { |dir| File.directory?(dir) }
paths.concat builtin_directories
paths.concat library_directories
end | ruby | def default_load_paths
paths = ["#{RADIANT_ROOT}/test/mocks/#{environment}"]
# Add the app's controller directory
paths.concat(Dir["#{RADIANT_ROOT}/app/controllers/"])
# Followed by the standard includes.
paths.concat %w(
app
app/metal
app/models
app/controllers
app/helpers
config
lib
vendor
).map { |dir| "#{RADIANT_ROOT}/#{dir}" }.select { |dir| File.directory?(dir) }
paths.concat builtin_directories
paths.concat library_directories
end | [
"def",
"default_load_paths",
"paths",
"=",
"[",
"\"#{RADIANT_ROOT}/test/mocks/#{environment}\"",
"]",
"# Add the app's controller directory",
"paths",
".",
"concat",
"(",
"Dir",
"[",
"\"#{RADIANT_ROOT}/app/controllers/\"",
"]",
")",
"# Followed by the standard includes.",
"paths",
".",
"concat",
"%w(",
"app",
"app/metal",
"app/models",
"app/controllers",
"app/helpers",
"config",
"lib",
"vendor",
")",
".",
"map",
"{",
"|",
"dir",
"|",
"\"#{RADIANT_ROOT}/#{dir}\"",
"}",
".",
"select",
"{",
"|",
"dir",
"|",
"File",
".",
"directory?",
"(",
"dir",
")",
"}",
"paths",
".",
"concat",
"builtin_directories",
"paths",
".",
"concat",
"library_directories",
"end"
] | Provide the load paths for the Radiant installation | [
"Provide",
"the",
"load",
"paths",
"for",
"the",
"Radiant",
"installation"
] | 5802d7bac2630a1959c463baa3aa7adcd0f497ee | https://github.com/radiant/radiant/blob/5802d7bac2630a1959c463baa3aa7adcd0f497ee/lib/radiant/engine.rb#L141-L161 | train |
radiant/radiant | lib/radiant/extension.rb | Radiant.Extension.extension_enabled? | def extension_enabled?(extension)
begin
extension = (extension.to_s.camelcase + 'Extension').constantize
extension.enabled?
rescue NameError
false
end
end | ruby | def extension_enabled?(extension)
begin
extension = (extension.to_s.camelcase + 'Extension').constantize
extension.enabled?
rescue NameError
false
end
end | [
"def",
"extension_enabled?",
"(",
"extension",
")",
"begin",
"extension",
"=",
"(",
"extension",
".",
"to_s",
".",
"camelcase",
"+",
"'Extension'",
")",
".",
"constantize",
"extension",
".",
"enabled?",
"rescue",
"NameError",
"false",
"end",
"end"
] | Determine if another extension is installed and up to date.
if MyExtension.extension_enabled?(:third_party)
ThirdPartyExtension.extend(MyExtension::IntegrationPoints)
end | [
"Determine",
"if",
"another",
"extension",
"is",
"installed",
"and",
"up",
"to",
"date",
"."
] | 5802d7bac2630a1959c463baa3aa7adcd0f497ee | https://github.com/radiant/radiant/blob/5802d7bac2630a1959c463baa3aa7adcd0f497ee/lib/radiant/extension.rb#L97-L104 | train |
radiant/radiant | lib/radiant/extension_path.rb | Radiant.ExtensionPath.check_subdirectory | def check_subdirectory(subpath)
subdirectory = File.join(path, subpath)
subdirectory if File.directory?(subdirectory)
end | ruby | def check_subdirectory(subpath)
subdirectory = File.join(path, subpath)
subdirectory if File.directory?(subdirectory)
end | [
"def",
"check_subdirectory",
"(",
"subpath",
")",
"subdirectory",
"=",
"File",
".",
"join",
"(",
"path",
",",
"subpath",
")",
"subdirectory",
"if",
"File",
".",
"directory?",
"(",
"subdirectory",
")",
"end"
] | If the supplied path within the extension root exists and is a directory, its absolute path is returned. Otherwise, nil. | [
"If",
"the",
"supplied",
"path",
"within",
"the",
"extension",
"root",
"exists",
"and",
"is",
"a",
"directory",
"its",
"absolute",
"path",
"is",
"returned",
".",
"Otherwise",
"nil",
"."
] | 5802d7bac2630a1959c463baa3aa7adcd0f497ee | https://github.com/radiant/radiant/blob/5802d7bac2630a1959c463baa3aa7adcd0f497ee/lib/radiant/extension_path.rb#L194-L197 | train |
radiant/radiant | lib/radiant/extension_loader.rb | Radiant.ExtensionLoader.load_extension | def load_extension(name)
extension_path = ExtensionPath.find(name)
begin
constant = "#{name}_extension".camelize
extension = constant.constantize
extension.unloadable
extension.path = extension_path
extension
rescue LoadError, NameError => e
$stderr.puts "Could not load extension: #{name}.\n#{e.inspect}"
nil
end
end | ruby | def load_extension(name)
extension_path = ExtensionPath.find(name)
begin
constant = "#{name}_extension".camelize
extension = constant.constantize
extension.unloadable
extension.path = extension_path
extension
rescue LoadError, NameError => e
$stderr.puts "Could not load extension: #{name}.\n#{e.inspect}"
nil
end
end | [
"def",
"load_extension",
"(",
"name",
")",
"extension_path",
"=",
"ExtensionPath",
".",
"find",
"(",
"name",
")",
"begin",
"constant",
"=",
"\"#{name}_extension\"",
".",
"camelize",
"extension",
"=",
"constant",
".",
"constantize",
"extension",
".",
"unloadable",
"extension",
".",
"path",
"=",
"extension_path",
"extension",
"rescue",
"LoadError",
",",
"NameError",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Could not load extension: #{name}.\\n#{e.inspect}\"",
"nil",
"end",
"end"
] | Loads the specified extension. | [
"Loads",
"the",
"specified",
"extension",
"."
] | 5802d7bac2630a1959c463baa3aa7adcd0f497ee | https://github.com/radiant/radiant/blob/5802d7bac2630a1959c463baa3aa7adcd0f497ee/lib/radiant/extension_loader.rb#L71-L83 | train |
radiant/radiant | app/helpers/radiant/application_helper.rb | Radiant.ApplicationHelper.pagination_for | def pagination_for(list, options={})
if list.respond_to? :total_pages
options = {
max_per_page: detail['pagination.max_per_page'] || 500,
depaginate: true
}.merge(options.symbolize_keys)
depaginate = options.delete(:depaginate) # supply depaginate: false to omit the 'show all' link
depagination_limit = options.delete(:max_per_page) # supply max_per_page: false to include the 'show all' link no matter how large the collection
html = will_paginate(list, will_paginate_options.merge(options))
if depaginate && list.total_pages > 1 && (!depagination_limit.blank? || list.total_entries <= depagination_limit.to_i)
html << content_tag(:div, link_to(t('show_all'), pp: 'all'), class: 'depaginate')
elsif depaginate && list.total_entries > depagination_limit.to_i
html = content_tag(:div, link_to("paginate", p: 1), class: 'pagination')
end
html
end
end | ruby | def pagination_for(list, options={})
if list.respond_to? :total_pages
options = {
max_per_page: detail['pagination.max_per_page'] || 500,
depaginate: true
}.merge(options.symbolize_keys)
depaginate = options.delete(:depaginate) # supply depaginate: false to omit the 'show all' link
depagination_limit = options.delete(:max_per_page) # supply max_per_page: false to include the 'show all' link no matter how large the collection
html = will_paginate(list, will_paginate_options.merge(options))
if depaginate && list.total_pages > 1 && (!depagination_limit.blank? || list.total_entries <= depagination_limit.to_i)
html << content_tag(:div, link_to(t('show_all'), pp: 'all'), class: 'depaginate')
elsif depaginate && list.total_entries > depagination_limit.to_i
html = content_tag(:div, link_to("paginate", p: 1), class: 'pagination')
end
html
end
end | [
"def",
"pagination_for",
"(",
"list",
",",
"options",
"=",
"{",
"}",
")",
"if",
"list",
".",
"respond_to?",
":total_pages",
"options",
"=",
"{",
"max_per_page",
":",
"detail",
"[",
"'pagination.max_per_page'",
"]",
"||",
"500",
",",
"depaginate",
":",
"true",
"}",
".",
"merge",
"(",
"options",
".",
"symbolize_keys",
")",
"depaginate",
"=",
"options",
".",
"delete",
"(",
":depaginate",
")",
"# supply depaginate: false to omit the 'show all' link",
"depagination_limit",
"=",
"options",
".",
"delete",
"(",
":max_per_page",
")",
"# supply max_per_page: false to include the 'show all' link no matter how large the collection",
"html",
"=",
"will_paginate",
"(",
"list",
",",
"will_paginate_options",
".",
"merge",
"(",
"options",
")",
")",
"if",
"depaginate",
"&&",
"list",
".",
"total_pages",
">",
"1",
"&&",
"(",
"!",
"depagination_limit",
".",
"blank?",
"||",
"list",
".",
"total_entries",
"<=",
"depagination_limit",
".",
"to_i",
")",
"html",
"<<",
"content_tag",
"(",
":div",
",",
"link_to",
"(",
"t",
"(",
"'show_all'",
")",
",",
"pp",
":",
"'all'",
")",
",",
"class",
":",
"'depaginate'",
")",
"elsif",
"depaginate",
"&&",
"list",
".",
"total_entries",
">",
"depagination_limit",
".",
"to_i",
"html",
"=",
"content_tag",
"(",
":div",
",",
"link_to",
"(",
"\"paginate\"",
",",
"p",
":",
"1",
")",
",",
"class",
":",
"'pagination'",
")",
"end",
"html",
"end",
"end"
] | returns the usual set of pagination links.
options are passed through to will_paginate
and a 'show all' depagination link is added if relevant. | [
"returns",
"the",
"usual",
"set",
"of",
"pagination",
"links",
".",
"options",
"are",
"passed",
"through",
"to",
"will_paginate",
"and",
"a",
"show",
"all",
"depagination",
"link",
"is",
"added",
"if",
"relevant",
"."
] | 5802d7bac2630a1959c463baa3aa7adcd0f497ee | https://github.com/radiant/radiant/blob/5802d7bac2630a1959c463baa3aa7adcd0f497ee/app/helpers/radiant/application_helper.rb#L216-L232 | train |
CrossRef/pdfextract | lib/pdf/extract/view/xml_view.rb | PdfExtract.XmlView.get_xml_attributes | def get_xml_attributes obj, parent=true
attribs = obj.reject { |k, _| @@ignored_attributes.include? k }
if parent
attribs = attribs.reject { |k, _| @@parent_ignored_attributes.include? k }
end
attribs = attribs.reject { |_, v| v.kind_of?(Hash) || v.kind_of?(Array) }
attribs.each_pair do |k, v|
if @@numeric_attributes.include?(k) || k.to_s =~ /.+_score/
attribs[k] = v.round(@render_options[:round])
end
end
attribs
end | ruby | def get_xml_attributes obj, parent=true
attribs = obj.reject { |k, _| @@ignored_attributes.include? k }
if parent
attribs = attribs.reject { |k, _| @@parent_ignored_attributes.include? k }
end
attribs = attribs.reject { |_, v| v.kind_of?(Hash) || v.kind_of?(Array) }
attribs.each_pair do |k, v|
if @@numeric_attributes.include?(k) || k.to_s =~ /.+_score/
attribs[k] = v.round(@render_options[:round])
end
end
attribs
end | [
"def",
"get_xml_attributes",
"obj",
",",
"parent",
"=",
"true",
"attribs",
"=",
"obj",
".",
"reject",
"{",
"|",
"k",
",",
"_",
"|",
"@@ignored_attributes",
".",
"include?",
"k",
"}",
"if",
"parent",
"attribs",
"=",
"attribs",
".",
"reject",
"{",
"|",
"k",
",",
"_",
"|",
"@@parent_ignored_attributes",
".",
"include?",
"k",
"}",
"end",
"attribs",
"=",
"attribs",
".",
"reject",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"kind_of?",
"(",
"Hash",
")",
"||",
"v",
".",
"kind_of?",
"(",
"Array",
")",
"}",
"attribs",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"@@numeric_attributes",
".",
"include?",
"(",
"k",
")",
"||",
"k",
".",
"to_s",
"=~",
"/",
"/",
"attribs",
"[",
"k",
"]",
"=",
"v",
".",
"round",
"(",
"@render_options",
"[",
":round",
"]",
")",
"end",
"end",
"attribs",
"end"
] | Return renderable attributes | [
"Return",
"renderable",
"attributes"
] | 8be42eb0f5f77904ddba49d26f3b241e9fb6cf90 | https://github.com/CrossRef/pdfextract/blob/8be42eb0f5f77904ddba49d26f3b241e9fb6cf90/lib/pdf/extract/view/xml_view.rb#L18-L30 | train |
lml/commontator | app/models/commontator/thread.rb | Commontator.Thread.clear | def clear
return if commontable.blank? || !is_closed?
new_thread = Thread.new
new_thread.commontable = commontable
with_lock do
self.commontable = nil
save!
new_thread.save!
subscriptions.each do |s|
s.thread = new_thread
s.save!
end
end
end | ruby | def clear
return if commontable.blank? || !is_closed?
new_thread = Thread.new
new_thread.commontable = commontable
with_lock do
self.commontable = nil
save!
new_thread.save!
subscriptions.each do |s|
s.thread = new_thread
s.save!
end
end
end | [
"def",
"clear",
"return",
"if",
"commontable",
".",
"blank?",
"||",
"!",
"is_closed?",
"new_thread",
"=",
"Thread",
".",
"new",
"new_thread",
".",
"commontable",
"=",
"commontable",
"with_lock",
"do",
"self",
".",
"commontable",
"=",
"nil",
"save!",
"new_thread",
".",
"save!",
"subscriptions",
".",
"each",
"do",
"|",
"s",
"|",
"s",
".",
"thread",
"=",
"new_thread",
"s",
".",
"save!",
"end",
"end",
"end"
] | Creates a new empty thread and assigns it to the commontable
The old thread is kept in the database for archival purposes | [
"Creates",
"a",
"new",
"empty",
"thread",
"and",
"assigns",
"it",
"to",
"the",
"commontable",
"The",
"old",
"thread",
"is",
"kept",
"in",
"the",
"database",
"for",
"archival",
"purposes"
] | 1cfc72bc4078fb3c92fa74987af219de583e82ff | https://github.com/lml/commontator/blob/1cfc72bc4078fb3c92fa74987af219de583e82ff/app/models/commontator/thread.rb#L119-L133 | train |
lml/commontator | app/models/commontator/thread.rb | Commontator.Thread.can_be_edited_by? | def can_be_edited_by?(user)
!commontable.nil? && !user.nil? && user.is_commontator &&\
config.thread_moderator_proc.call(self, user)
end | ruby | def can_be_edited_by?(user)
!commontable.nil? && !user.nil? && user.is_commontator &&\
config.thread_moderator_proc.call(self, user)
end | [
"def",
"can_be_edited_by?",
"(",
"user",
")",
"!",
"commontable",
".",
"nil?",
"&&",
"!",
"user",
".",
"nil?",
"&&",
"user",
".",
"is_commontator",
"&&",
"config",
".",
"thread_moderator_proc",
".",
"call",
"(",
"self",
",",
"user",
")",
"end"
] | Thread moderator capabilities | [
"Thread",
"moderator",
"capabilities"
] | 1cfc72bc4078fb3c92fa74987af219de583e82ff | https://github.com/lml/commontator/blob/1cfc72bc4078fb3c92fa74987af219de583e82ff/app/models/commontator/thread.rb#L147-L150 | train |
piotrmurach/strings | lib/strings/truncate.rb | Strings.Truncate.shorten | def shorten(original_chars, chars, length_without_trailing)
truncated = []
char_width = display_width(chars[0])
while length_without_trailing - char_width > 0
orig_char = original_chars.shift
char = chars.shift
break unless char
while orig_char != char # consume ansi
ansi = true
truncated << orig_char
orig_char = original_chars.shift
end
truncated << char
char_width = display_width(char)
length_without_trailing -= char_width
end
truncated << ["\e[0m"] if ansi
truncated
end | ruby | def shorten(original_chars, chars, length_without_trailing)
truncated = []
char_width = display_width(chars[0])
while length_without_trailing - char_width > 0
orig_char = original_chars.shift
char = chars.shift
break unless char
while orig_char != char # consume ansi
ansi = true
truncated << orig_char
orig_char = original_chars.shift
end
truncated << char
char_width = display_width(char)
length_without_trailing -= char_width
end
truncated << ["\e[0m"] if ansi
truncated
end | [
"def",
"shorten",
"(",
"original_chars",
",",
"chars",
",",
"length_without_trailing",
")",
"truncated",
"=",
"[",
"]",
"char_width",
"=",
"display_width",
"(",
"chars",
"[",
"0",
"]",
")",
"while",
"length_without_trailing",
"-",
"char_width",
">",
"0",
"orig_char",
"=",
"original_chars",
".",
"shift",
"char",
"=",
"chars",
".",
"shift",
"break",
"unless",
"char",
"while",
"orig_char",
"!=",
"char",
"# consume ansi",
"ansi",
"=",
"true",
"truncated",
"<<",
"orig_char",
"orig_char",
"=",
"original_chars",
".",
"shift",
"end",
"truncated",
"<<",
"char",
"char_width",
"=",
"display_width",
"(",
"char",
")",
"length_without_trailing",
"-=",
"char_width",
"end",
"truncated",
"<<",
"[",
"\"\\e[0m\"",
"]",
"if",
"ansi",
"truncated",
"end"
] | Perform actual shortening of the text
@return [String]
@api private | [
"Perform",
"actual",
"shortening",
"of",
"the",
"text"
] | 1166dabcdd369600b37084e432dce7868b9a6759 | https://github.com/piotrmurach/strings/blob/1166dabcdd369600b37084e432dce7868b9a6759/lib/strings/truncate.rb#L71-L89 | train |
piotrmurach/strings | lib/strings/pad.rb | Strings.Pad.pad | def pad(text, padding, fill: SPACE, separator: NEWLINE)
padding = Strings::Padder.parse(padding)
text_copy = text.dup
line_width = max_line_length(text, separator)
output = []
filler_line = fill * line_width
padding.top.times do
output << pad_around(filler_line, padding, fill: fill)
end
text_copy.split(separator).each do |line|
output << pad_around(line, padding, fill: fill)
end
padding.bottom.times do
output << pad_around(filler_line, padding, fill: fill)
end
output.join(separator)
end | ruby | def pad(text, padding, fill: SPACE, separator: NEWLINE)
padding = Strings::Padder.parse(padding)
text_copy = text.dup
line_width = max_line_length(text, separator)
output = []
filler_line = fill * line_width
padding.top.times do
output << pad_around(filler_line, padding, fill: fill)
end
text_copy.split(separator).each do |line|
output << pad_around(line, padding, fill: fill)
end
padding.bottom.times do
output << pad_around(filler_line, padding, fill: fill)
end
output.join(separator)
end | [
"def",
"pad",
"(",
"text",
",",
"padding",
",",
"fill",
":",
"SPACE",
",",
"separator",
":",
"NEWLINE",
")",
"padding",
"=",
"Strings",
"::",
"Padder",
".",
"parse",
"(",
"padding",
")",
"text_copy",
"=",
"text",
".",
"dup",
"line_width",
"=",
"max_line_length",
"(",
"text",
",",
"separator",
")",
"output",
"=",
"[",
"]",
"filler_line",
"=",
"fill",
"*",
"line_width",
"padding",
".",
"top",
".",
"times",
"do",
"output",
"<<",
"pad_around",
"(",
"filler_line",
",",
"padding",
",",
"fill",
":",
"fill",
")",
"end",
"text_copy",
".",
"split",
"(",
"separator",
")",
".",
"each",
"do",
"|",
"line",
"|",
"output",
"<<",
"pad_around",
"(",
"line",
",",
"padding",
",",
"fill",
":",
"fill",
")",
"end",
"padding",
".",
"bottom",
".",
"times",
"do",
"output",
"<<",
"pad_around",
"(",
"filler_line",
",",
"padding",
",",
"fill",
":",
"fill",
")",
"end",
"output",
".",
"join",
"(",
"separator",
")",
"end"
] | Apply padding to multiline text with ANSI codes
@param [String] text
the text to pad out
@param [Integer, Array[Integer]] padding
the padding to apply to text
@example
text = "Ignorance is the parent of fear."
Strings::Pad.pad(text, [1, 2], fill: "*")
# =>
# "************************************\n"
# "**Ignorance is the parent of fear.**\n"
# "************************************\n"
@return [String]
@api private | [
"Apply",
"padding",
"to",
"multiline",
"text",
"with",
"ANSI",
"codes"
] | 1166dabcdd369600b37084e432dce7868b9a6759 | https://github.com/piotrmurach/strings/blob/1166dabcdd369600b37084e432dce7868b9a6759/lib/strings/pad.rb#L34-L55 | train |
piotrmurach/strings | lib/strings/pad.rb | Strings.Pad.pad_around | def pad_around(text, padding, fill: SPACE)
fill * padding.left + text + fill * padding.right
end | ruby | def pad_around(text, padding, fill: SPACE)
fill * padding.left + text + fill * padding.right
end | [
"def",
"pad_around",
"(",
"text",
",",
"padding",
",",
"fill",
":",
"SPACE",
")",
"fill",
"*",
"padding",
".",
"left",
"+",
"text",
"+",
"fill",
"*",
"padding",
".",
"right",
"end"
] | Apply padding to left and right side of string
@param [String] text
@return [String]
@api private | [
"Apply",
"padding",
"to",
"left",
"and",
"right",
"side",
"of",
"string"
] | 1166dabcdd369600b37084e432dce7868b9a6759 | https://github.com/piotrmurach/strings/blob/1166dabcdd369600b37084e432dce7868b9a6759/lib/strings/pad.rb#L65-L67 | train |
piotrmurach/strings | lib/strings/align.rb | Strings.Align.align_left | def align_left(text, width, fill: SPACE, separator: NEWLINE)
return if width.nil?
each_line(text, separator) do |line|
width_diff = width - display_width(line)
if width_diff > 0
line + fill * width_diff
else
line
end
end
end | ruby | def align_left(text, width, fill: SPACE, separator: NEWLINE)
return if width.nil?
each_line(text, separator) do |line|
width_diff = width - display_width(line)
if width_diff > 0
line + fill * width_diff
else
line
end
end
end | [
"def",
"align_left",
"(",
"text",
",",
"width",
",",
"fill",
":",
"SPACE",
",",
"separator",
":",
"NEWLINE",
")",
"return",
"if",
"width",
".",
"nil?",
"each_line",
"(",
"text",
",",
"separator",
")",
"do",
"|",
"line",
"|",
"width_diff",
"=",
"width",
"-",
"display_width",
"(",
"line",
")",
"if",
"width_diff",
">",
"0",
"line",
"+",
"fill",
"*",
"width_diff",
"else",
"line",
"end",
"end",
"end"
] | Aligns text to the left at given length
@return [String]
@api public | [
"Aligns",
"text",
"to",
"the",
"left",
"at",
"given",
"length"
] | 1166dabcdd369600b37084e432dce7868b9a6759 | https://github.com/piotrmurach/strings/blob/1166dabcdd369600b37084e432dce7868b9a6759/lib/strings/align.rb#L65-L75 | train |
piotrmurach/strings | lib/strings/align.rb | Strings.Align.align_center | def align_center(text, width, fill: SPACE, separator: NEWLINE)
return text if width.nil?
each_line(text, separator) do |line|
width_diff = width - display_width(line)
if width_diff > 0
right_count = (width_diff.to_f / 2).ceil
left_count = width_diff - right_count
[fill * left_count, line, fill * right_count].join
else
line
end
end
end | ruby | def align_center(text, width, fill: SPACE, separator: NEWLINE)
return text if width.nil?
each_line(text, separator) do |line|
width_diff = width - display_width(line)
if width_diff > 0
right_count = (width_diff.to_f / 2).ceil
left_count = width_diff - right_count
[fill * left_count, line, fill * right_count].join
else
line
end
end
end | [
"def",
"align_center",
"(",
"text",
",",
"width",
",",
"fill",
":",
"SPACE",
",",
"separator",
":",
"NEWLINE",
")",
"return",
"text",
"if",
"width",
".",
"nil?",
"each_line",
"(",
"text",
",",
"separator",
")",
"do",
"|",
"line",
"|",
"width_diff",
"=",
"width",
"-",
"display_width",
"(",
"line",
")",
"if",
"width_diff",
">",
"0",
"right_count",
"=",
"(",
"width_diff",
".",
"to_f",
"/",
"2",
")",
".",
"ceil",
"left_count",
"=",
"width_diff",
"-",
"right_count",
"[",
"fill",
"*",
"left_count",
",",
"line",
",",
"fill",
"*",
"right_count",
"]",
".",
"join",
"else",
"line",
"end",
"end",
"end"
] | Centers text within the width
@return [String]
@api public | [
"Centers",
"text",
"within",
"the",
"width"
] | 1166dabcdd369600b37084e432dce7868b9a6759 | https://github.com/piotrmurach/strings/blob/1166dabcdd369600b37084e432dce7868b9a6759/lib/strings/align.rb#L83-L95 | train |
piotrmurach/strings | lib/strings/align.rb | Strings.Align.each_line | def each_line(text, separator)
lines = text.split(separator)
return yield(text) if text.empty?
lines.reduce([]) do |aligned, line|
aligned << yield(line)
end.join(separator)
end | ruby | def each_line(text, separator)
lines = text.split(separator)
return yield(text) if text.empty?
lines.reduce([]) do |aligned, line|
aligned << yield(line)
end.join(separator)
end | [
"def",
"each_line",
"(",
"text",
",",
"separator",
")",
"lines",
"=",
"text",
".",
"split",
"(",
"separator",
")",
"return",
"yield",
"(",
"text",
")",
"if",
"text",
".",
"empty?",
"lines",
".",
"reduce",
"(",
"[",
"]",
")",
"do",
"|",
"aligned",
",",
"line",
"|",
"aligned",
"<<",
"yield",
"(",
"line",
")",
"end",
".",
"join",
"(",
"separator",
")",
"end"
] | Enumerate text line by line
@param [String] text
@return [String]
@api private | [
"Enumerate",
"text",
"line",
"by",
"line"
] | 1166dabcdd369600b37084e432dce7868b9a6759 | https://github.com/piotrmurach/strings/blob/1166dabcdd369600b37084e432dce7868b9a6759/lib/strings/align.rb#L123-L129 | train |
nylas/nylas-ruby | lib/nylas/http_client.rb | Nylas.HttpClient.execute | def execute(method:, path: nil, headers: {}, query: {}, payload: nil)
timeout = ENDPOINT_TIMEOUTS.fetch(path, 230)
request = build_request(
method: method,
path: path,
headers: headers,
query: query,
payload: payload,
timeout: timeout
)
rest_client_execute(**request) do |response, _request, result|
response = parse_response(response)
handle_failed_response(result: result, response: response)
response
end
end | ruby | def execute(method:, path: nil, headers: {}, query: {}, payload: nil)
timeout = ENDPOINT_TIMEOUTS.fetch(path, 230)
request = build_request(
method: method,
path: path,
headers: headers,
query: query,
payload: payload,
timeout: timeout
)
rest_client_execute(**request) do |response, _request, result|
response = parse_response(response)
handle_failed_response(result: result, response: response)
response
end
end | [
"def",
"execute",
"(",
"method",
":",
",",
"path",
":",
"nil",
",",
"headers",
":",
"{",
"}",
",",
"query",
":",
"{",
"}",
",",
"payload",
":",
"nil",
")",
"timeout",
"=",
"ENDPOINT_TIMEOUTS",
".",
"fetch",
"(",
"path",
",",
"230",
")",
"request",
"=",
"build_request",
"(",
"method",
":",
"method",
",",
"path",
":",
"path",
",",
"headers",
":",
"headers",
",",
"query",
":",
"query",
",",
"payload",
":",
"payload",
",",
"timeout",
":",
"timeout",
")",
"rest_client_execute",
"(",
"**",
"request",
")",
"do",
"|",
"response",
",",
"_request",
",",
"result",
"|",
"response",
"=",
"parse_response",
"(",
"response",
")",
"handle_failed_response",
"(",
"result",
":",
"result",
",",
"response",
":",
"response",
")",
"response",
"end",
"end"
] | Sends a request to the Nylas API and rai
@param method [Symbol] HTTP method for the API call. Either :get, :post, :delete, or :patch
@param path [String] (Optional, defaults to nil) - Relative path from the API Base. Preferred way to
execute arbitrary or-not-yet-SDK-ified API commands.
@param headers [Hash] (Optional, defaults to {}) - Additional HTTP headers to include in the payload.
@param query [Hash] (Optional, defaults to {}) - Hash of names and values to include in the query
section of the URI fragment
@param payload [String,Hash] (Optional, defaults to nil) - Body to send with the request.
@return [Array Hash Stringn]
rubocop:disable Metrics/MethodLength | [
"Sends",
"a",
"request",
"to",
"the",
"Nylas",
"API",
"and",
"rai"
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/http_client.rb#L72-L87 | train |
nylas/nylas-ruby | lib/nylas/http_client.rb | Nylas.HttpClient.get | def get(path: nil, headers: {}, query: {})
execute(method: :get, path: path, query: query, headers: headers)
end | ruby | def get(path: nil, headers: {}, query: {})
execute(method: :get, path: path, query: query, headers: headers)
end | [
"def",
"get",
"(",
"path",
":",
"nil",
",",
"headers",
":",
"{",
"}",
",",
"query",
":",
"{",
"}",
")",
"execute",
"(",
"method",
":",
":get",
",",
"path",
":",
"path",
",",
"query",
":",
"query",
",",
"headers",
":",
"headers",
")",
"end"
] | Syntactical sugar for making GET requests via the API.
@see #execute | [
"Syntactical",
"sugar",
"for",
"making",
"GET",
"requests",
"via",
"the",
"API",
"."
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/http_client.rb#L101-L103 | train |
nylas/nylas-ruby | lib/nylas/http_client.rb | Nylas.HttpClient.post | def post(path: nil, payload: nil, headers: {}, query: {})
execute(method: :post, path: path, headers: headers, query: query, payload: payload)
end | ruby | def post(path: nil, payload: nil, headers: {}, query: {})
execute(method: :post, path: path, headers: headers, query: query, payload: payload)
end | [
"def",
"post",
"(",
"path",
":",
"nil",
",",
"payload",
":",
"nil",
",",
"headers",
":",
"{",
"}",
",",
"query",
":",
"{",
"}",
")",
"execute",
"(",
"method",
":",
":post",
",",
"path",
":",
"path",
",",
"headers",
":",
"headers",
",",
"query",
":",
"query",
",",
"payload",
":",
"payload",
")",
"end"
] | Syntactical sugar for making POST requests via the API.
@see #execute | [
"Syntactical",
"sugar",
"for",
"making",
"POST",
"requests",
"via",
"the",
"API",
"."
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/http_client.rb#L107-L109 | train |
nylas/nylas-ruby | lib/nylas/http_client.rb | Nylas.HttpClient.put | def put(path: nil, payload:, headers: {}, query: {})
execute(method: :put, path: path, headers: headers, query: query, payload: payload)
end | ruby | def put(path: nil, payload:, headers: {}, query: {})
execute(method: :put, path: path, headers: headers, query: query, payload: payload)
end | [
"def",
"put",
"(",
"path",
":",
"nil",
",",
"payload",
":",
",",
"headers",
":",
"{",
"}",
",",
"query",
":",
"{",
"}",
")",
"execute",
"(",
"method",
":",
":put",
",",
"path",
":",
"path",
",",
"headers",
":",
"headers",
",",
"query",
":",
"query",
",",
"payload",
":",
"payload",
")",
"end"
] | Syntactical sugar for making PUT requests via the API.
@see #execute | [
"Syntactical",
"sugar",
"for",
"making",
"PUT",
"requests",
"via",
"the",
"API",
"."
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/http_client.rb#L113-L115 | train |
nylas/nylas-ruby | lib/nylas/http_client.rb | Nylas.HttpClient.delete | def delete(path: nil, payload: nil, headers: {}, query: {})
execute(method: :delete, path: path, headers: headers, query: query, payload: payload)
end | ruby | def delete(path: nil, payload: nil, headers: {}, query: {})
execute(method: :delete, path: path, headers: headers, query: query, payload: payload)
end | [
"def",
"delete",
"(",
"path",
":",
"nil",
",",
"payload",
":",
"nil",
",",
"headers",
":",
"{",
"}",
",",
"query",
":",
"{",
"}",
")",
"execute",
"(",
"method",
":",
":delete",
",",
"path",
":",
"path",
",",
"headers",
":",
"headers",
",",
"query",
":",
"query",
",",
"payload",
":",
"payload",
")",
"end"
] | Syntactical sugar for making DELETE requests via the API.
@see #execute | [
"Syntactical",
"sugar",
"for",
"making",
"DELETE",
"requests",
"via",
"the",
"API",
"."
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/http_client.rb#L119-L121 | train |
nylas/nylas-ruby | lib/nylas/collection.rb | Nylas.Collection.where | def where(filters)
raise ModelNotFilterableError, model unless model.filterable?
self.class.new(model: model, api: api, constraints: constraints.merge(where: filters))
end | ruby | def where(filters)
raise ModelNotFilterableError, model unless model.filterable?
self.class.new(model: model, api: api, constraints: constraints.merge(where: filters))
end | [
"def",
"where",
"(",
"filters",
")",
"raise",
"ModelNotFilterableError",
",",
"model",
"unless",
"model",
".",
"filterable?",
"self",
".",
"class",
".",
"new",
"(",
"model",
":",
"model",
",",
"api",
":",
"api",
",",
"constraints",
":",
"constraints",
".",
"merge",
"(",
"where",
":",
"filters",
")",
")",
"end"
] | Merges in additional filters when querying the collection
@return [Collection<Model>] | [
"Merges",
"in",
"additional",
"filters",
"when",
"querying",
"the",
"collection"
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/collection.rb#L30-L34 | train |
nylas/nylas-ruby | lib/nylas/collection.rb | Nylas.Collection.raw | def raw
raise ModelNotAvailableAsRawError, model unless model.exposable_as_raw?
self.class.new(model: model, api: api, constraints: constraints.merge(accept: model.raw_mime_type))
end | ruby | def raw
raise ModelNotAvailableAsRawError, model unless model.exposable_as_raw?
self.class.new(model: model, api: api, constraints: constraints.merge(accept: model.raw_mime_type))
end | [
"def",
"raw",
"raise",
"ModelNotAvailableAsRawError",
",",
"model",
"unless",
"model",
".",
"exposable_as_raw?",
"self",
".",
"class",
".",
"new",
"(",
"model",
":",
"model",
",",
"api",
":",
"api",
",",
"constraints",
":",
"constraints",
".",
"merge",
"(",
"accept",
":",
"model",
".",
"raw_mime_type",
")",
")",
"end"
] | The collection now returns a string representation of the model in a particular mime type instead of
Model objects
@return [Collection<String>] | [
"The",
"collection",
"now",
"returns",
"a",
"string",
"representation",
"of",
"the",
"model",
"in",
"a",
"particular",
"mime",
"type",
"instead",
"of",
"Model",
"objects"
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/collection.rb#L45-L49 | train |
nylas/nylas-ruby | lib/nylas/collection.rb | Nylas.Collection.each | def each
return enum_for(:each) unless block_given?
execute.each do |result|
yield(model.new(result.merge(api: api)))
end
end | ruby | def each
return enum_for(:each) unless block_given?
execute.each do |result|
yield(model.new(result.merge(api: api)))
end
end | [
"def",
"each",
"return",
"enum_for",
"(",
":each",
")",
"unless",
"block_given?",
"execute",
".",
"each",
"do",
"|",
"result",
"|",
"yield",
"(",
"model",
".",
"new",
"(",
"result",
".",
"merge",
"(",
"api",
":",
"api",
")",
")",
")",
"end",
"end"
] | Iterates over a single page of results based upon current pagination settings | [
"Iterates",
"over",
"a",
"single",
"page",
"of",
"results",
"based",
"upon",
"current",
"pagination",
"settings"
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/collection.rb#L67-L73 | train |
nylas/nylas-ruby | lib/nylas/collection.rb | Nylas.Collection.find_each | def find_each
return enum_for(:find_each) unless block_given?
query = self
accumulated = 0
while query
results = query.each do |instance|
yield(instance)
end
accumulated += results.length
query = query.next_page(accumulated: accumulated, current_page: results)
end
end | ruby | def find_each
return enum_for(:find_each) unless block_given?
query = self
accumulated = 0
while query
results = query.each do |instance|
yield(instance)
end
accumulated += results.length
query = query.next_page(accumulated: accumulated, current_page: results)
end
end | [
"def",
"find_each",
"return",
"enum_for",
"(",
":find_each",
")",
"unless",
"block_given?",
"query",
"=",
"self",
"accumulated",
"=",
"0",
"while",
"query",
"results",
"=",
"query",
".",
"each",
"do",
"|",
"instance",
"|",
"yield",
"(",
"instance",
")",
"end",
"accumulated",
"+=",
"results",
".",
"length",
"query",
"=",
"query",
".",
"next_page",
"(",
"accumulated",
":",
"accumulated",
",",
"current_page",
":",
"results",
")",
"end",
"end"
] | Iterates over every result that meets the filters, retrieving a page at a time | [
"Iterates",
"over",
"every",
"result",
"that",
"meets",
"the",
"filters",
"retrieving",
"a",
"page",
"at",
"a",
"time"
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/collection.rb#L84-L98 | train |
nylas/nylas-ruby | lib/nylas/file.rb | Nylas.File.download! | def download!
return download if file.nil?
file.close
file.unlink
self.file = nil
download
end | ruby | def download!
return download if file.nil?
file.close
file.unlink
self.file = nil
download
end | [
"def",
"download!",
"return",
"download",
"if",
"file",
".",
"nil?",
"file",
".",
"close",
"file",
".",
"unlink",
"self",
".",
"file",
"=",
"nil",
"download",
"end"
] | Redownloads a file even if it's been cached. Closes and unlinks the tempfile to help memory usage. | [
"Redownloads",
"a",
"file",
"even",
"if",
"it",
"s",
"been",
"cached",
".",
"Closes",
"and",
"unlinks",
"the",
"tempfile",
"to",
"help",
"memory",
"usage",
"."
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/file.rb#L32-L39 | train |
nylas/nylas-ruby | lib/nylas/api.rb | Nylas.API.revoke | def revoke(access_token)
response = client.as(access_token).post(path: "/oauth/revoke")
response.code == 200 && response.empty?
end | ruby | def revoke(access_token)
response = client.as(access_token).post(path: "/oauth/revoke")
response.code == 200 && response.empty?
end | [
"def",
"revoke",
"(",
"access_token",
")",
"response",
"=",
"client",
".",
"as",
"(",
"access_token",
")",
".",
"post",
"(",
"path",
":",
"\"/oauth/revoke\"",
")",
"response",
".",
"code",
"==",
"200",
"&&",
"response",
".",
"empty?",
"end"
] | Revokes access to the Nylas API for the given access token
@return [Boolean] | [
"Revokes",
"access",
"to",
"the",
"Nylas",
"API",
"for",
"the",
"given",
"access",
"token"
] | 5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d | https://github.com/nylas/nylas-ruby/blob/5453cf9b2e9d80ee55e38ff5a6c8b19b8d5c262d/lib/nylas/api.rb#L97-L100 | train |
Foodcritic/foodcritic | lib/foodcritic/command_line.rb | FoodCritic.CommandLine.valid_paths? | def valid_paths?
paths = options[:cookbook_paths] + options[:role_paths] +
options[:environment_paths]
paths.any? && paths.all? { |path| File.exist?(path) }
end | ruby | def valid_paths?
paths = options[:cookbook_paths] + options[:role_paths] +
options[:environment_paths]
paths.any? && paths.all? { |path| File.exist?(path) }
end | [
"def",
"valid_paths?",
"paths",
"=",
"options",
"[",
":cookbook_paths",
"]",
"+",
"options",
"[",
":role_paths",
"]",
"+",
"options",
"[",
":environment_paths",
"]",
"paths",
".",
"any?",
"&&",
"paths",
".",
"all?",
"{",
"|",
"path",
"|",
"File",
".",
"exist?",
"(",
"path",
")",
"}",
"end"
] | If the paths provided are valid
@return [Boolean] True if the paths exist. | [
"If",
"the",
"paths",
"provided",
"are",
"valid"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/command_line.rb#L147-L151 | train |
Foodcritic/foodcritic | lib/foodcritic/command_line.rb | FoodCritic.CommandLine.valid_grammar? | def valid_grammar?
return true unless options.key?(:search_grammar)
return false unless File.exist?(options[:search_grammar])
search = FoodCritic::Chef::Search.new
search.create_parser([options[:search_grammar]])
search.parser?
end | ruby | def valid_grammar?
return true unless options.key?(:search_grammar)
return false unless File.exist?(options[:search_grammar])
search = FoodCritic::Chef::Search.new
search.create_parser([options[:search_grammar]])
search.parser?
end | [
"def",
"valid_grammar?",
"return",
"true",
"unless",
"options",
".",
"key?",
"(",
":search_grammar",
")",
"return",
"false",
"unless",
"File",
".",
"exist?",
"(",
"options",
"[",
":search_grammar",
"]",
")",
"search",
"=",
"FoodCritic",
"::",
"Chef",
"::",
"Search",
".",
"new",
"search",
".",
"create_parser",
"(",
"[",
"options",
"[",
":search_grammar",
"]",
"]",
")",
"search",
".",
"parser?",
"end"
] | Is the search grammar specified valid?
@return [Boolean] True if the grammar has not been provided or can be
loaded. | [
"Is",
"the",
"search",
"grammar",
"specified",
"valid?"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/command_line.rb#L157-L163 | train |
Foodcritic/foodcritic | lib/foodcritic/linter.rb | FoodCritic.Linter.list | def list(options = {})
options = setup_defaults(options)
@options = options
load_rules
if options[:tags].any?
@rules = active_rules(options[:tags])
end
RuleList.new(@rules)
end | ruby | def list(options = {})
options = setup_defaults(options)
@options = options
load_rules
if options[:tags].any?
@rules = active_rules(options[:tags])
end
RuleList.new(@rules)
end | [
"def",
"list",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"setup_defaults",
"(",
"options",
")",
"@options",
"=",
"options",
"load_rules",
"if",
"options",
"[",
":tags",
"]",
".",
"any?",
"@rules",
"=",
"active_rules",
"(",
"options",
"[",
":tags",
"]",
")",
"end",
"RuleList",
".",
"new",
"(",
"@rules",
")",
"end"
] | List the rules that are currently in effect.
The `options` are a hash where the valid keys are:
* `:include_rules` - Paths to additional rules to apply
* `:search_gems - If true then search for custom rules in installed gems.
* `:tags` - The tags to filter rules based on | [
"List",
"the",
"rules",
"that",
"are",
"currently",
"in",
"effect",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/linter.rb#L42-L52 | train |
Foodcritic/foodcritic | lib/foodcritic/linter.rb | FoodCritic.Linter.check | def check(options = {})
options = setup_defaults(options)
@options = options
@chef_version = options[:chef_version] || DEFAULT_CHEF_VERSION
warnings = []; last_dir = nil; matched_rule_tags = Set.new
load_rules
paths = specified_paths!(options)
# Loop through each file to be processed and apply the rules
files = files_to_process(paths)
if options[:progress]
puts "Checking #{files.count} files"
end
files.each do |p|
relevant_tags = if options[:tags].any?
options[:tags]
else
rule_file_tags(p[:filename])
end
progress = "."
active_rules(relevant_tags).each do |rule|
state = {
path_type: p[:path_type],
file: p[:filename],
ast: read_ast(p[:filename]),
rule: rule,
last_dir: last_dir,
}
matches = if p[:path_type] == :cookbook
cookbook_matches(state)
else
other_matches(state)
end
matches = remove_ignored(matches, state[:rule], state[:file])
progress = "x" if matches.any?
# Convert the matches into warnings
matches.each do |match|
warnings << Warning.new(state[:rule],
{ filename: state[:file] }.merge(match),
options)
matched_rule_tags << state[:rule].tags
end
end
putc progress if options[:progress]
last_dir = cookbook_dir(p[:filename])
end
puts "" if options[:progress]
Review.new(paths, warnings)
end | ruby | def check(options = {})
options = setup_defaults(options)
@options = options
@chef_version = options[:chef_version] || DEFAULT_CHEF_VERSION
warnings = []; last_dir = nil; matched_rule_tags = Set.new
load_rules
paths = specified_paths!(options)
# Loop through each file to be processed and apply the rules
files = files_to_process(paths)
if options[:progress]
puts "Checking #{files.count} files"
end
files.each do |p|
relevant_tags = if options[:tags].any?
options[:tags]
else
rule_file_tags(p[:filename])
end
progress = "."
active_rules(relevant_tags).each do |rule|
state = {
path_type: p[:path_type],
file: p[:filename],
ast: read_ast(p[:filename]),
rule: rule,
last_dir: last_dir,
}
matches = if p[:path_type] == :cookbook
cookbook_matches(state)
else
other_matches(state)
end
matches = remove_ignored(matches, state[:rule], state[:file])
progress = "x" if matches.any?
# Convert the matches into warnings
matches.each do |match|
warnings << Warning.new(state[:rule],
{ filename: state[:file] }.merge(match),
options)
matched_rule_tags << state[:rule].tags
end
end
putc progress if options[:progress]
last_dir = cookbook_dir(p[:filename])
end
puts "" if options[:progress]
Review.new(paths, warnings)
end | [
"def",
"check",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"setup_defaults",
"(",
"options",
")",
"@options",
"=",
"options",
"@chef_version",
"=",
"options",
"[",
":chef_version",
"]",
"||",
"DEFAULT_CHEF_VERSION",
"warnings",
"=",
"[",
"]",
";",
"last_dir",
"=",
"nil",
";",
"matched_rule_tags",
"=",
"Set",
".",
"new",
"load_rules",
"paths",
"=",
"specified_paths!",
"(",
"options",
")",
"# Loop through each file to be processed and apply the rules",
"files",
"=",
"files_to_process",
"(",
"paths",
")",
"if",
"options",
"[",
":progress",
"]",
"puts",
"\"Checking #{files.count} files\"",
"end",
"files",
".",
"each",
"do",
"|",
"p",
"|",
"relevant_tags",
"=",
"if",
"options",
"[",
":tags",
"]",
".",
"any?",
"options",
"[",
":tags",
"]",
"else",
"rule_file_tags",
"(",
"p",
"[",
":filename",
"]",
")",
"end",
"progress",
"=",
"\".\"",
"active_rules",
"(",
"relevant_tags",
")",
".",
"each",
"do",
"|",
"rule",
"|",
"state",
"=",
"{",
"path_type",
":",
"p",
"[",
":path_type",
"]",
",",
"file",
":",
"p",
"[",
":filename",
"]",
",",
"ast",
":",
"read_ast",
"(",
"p",
"[",
":filename",
"]",
")",
",",
"rule",
":",
"rule",
",",
"last_dir",
":",
"last_dir",
",",
"}",
"matches",
"=",
"if",
"p",
"[",
":path_type",
"]",
"==",
":cookbook",
"cookbook_matches",
"(",
"state",
")",
"else",
"other_matches",
"(",
"state",
")",
"end",
"matches",
"=",
"remove_ignored",
"(",
"matches",
",",
"state",
"[",
":rule",
"]",
",",
"state",
"[",
":file",
"]",
")",
"progress",
"=",
"\"x\"",
"if",
"matches",
".",
"any?",
"# Convert the matches into warnings",
"matches",
".",
"each",
"do",
"|",
"match",
"|",
"warnings",
"<<",
"Warning",
".",
"new",
"(",
"state",
"[",
":rule",
"]",
",",
"{",
"filename",
":",
"state",
"[",
":file",
"]",
"}",
".",
"merge",
"(",
"match",
")",
",",
"options",
")",
"matched_rule_tags",
"<<",
"state",
"[",
":rule",
"]",
".",
"tags",
"end",
"end",
"putc",
"progress",
"if",
"options",
"[",
":progress",
"]",
"last_dir",
"=",
"cookbook_dir",
"(",
"p",
"[",
":filename",
"]",
")",
"end",
"puts",
"\"\"",
"if",
"options",
"[",
":progress",
"]",
"Review",
".",
"new",
"(",
"paths",
",",
"warnings",
")",
"end"
] | Review the cookbooks at the provided path, identifying potential
improvements.
The `options` are a hash where the valid keys are:
* `:cookbook_paths` - Cookbook paths to lint
* `:role_paths` - Role paths to lint
* `:include_rules` - Paths to additional rules to apply
* `:search_gems - If true then search for custom rules in installed gems.
* `:tags` - The tags to filter rules based on
* `:fail_tags` - The tags to fail the build on
* `:exclude_paths` - Paths to exclude from linting | [
"Review",
"the",
"cookbooks",
"at",
"the",
"provided",
"path",
"identifying",
"potential",
"improvements",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/linter.rb#L67-L128 | train |
Foodcritic/foodcritic | lib/foodcritic/linter.rb | FoodCritic.Linter.applies_to_version? | def applies_to_version?(rule, version)
return true unless version
rule.applies_to.yield(Gem::Version.create(version))
end | ruby | def applies_to_version?(rule, version)
return true unless version
rule.applies_to.yield(Gem::Version.create(version))
end | [
"def",
"applies_to_version?",
"(",
"rule",
",",
"version",
")",
"return",
"true",
"unless",
"version",
"rule",
".",
"applies_to",
".",
"yield",
"(",
"Gem",
"::",
"Version",
".",
"create",
"(",
"version",
")",
")",
"end"
] | Some rules are version specific. | [
"Some",
"rules",
"are",
"version",
"specific",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/linter.rb#L197-L200 | train |
Foodcritic/foodcritic | lib/foodcritic/linter.rb | FoodCritic.Linter.rule_file_tags | def rule_file_tags(file)
cookbook = cookbook_dir(file)
@tag_cache ||= {}
# lookup the tags in the cache has and return that if we find something
cb_tags = @tag_cache[cookbook]
return cb_tags unless cb_tags.nil?
# if a rule file has been specified use that. Otherwise use the .foodcritic file in the CB
tags = if @options[:rule_file]
raise "ERROR: Could not find the specified rule file at #{@options[:rule_file]}" unless File.exist?(@options[:rule_file])
parse_rule_file(@options[:rule_file])
else
File.exist?("#{cookbook}/.foodcritic") ? parse_rule_file("#{cookbook}/.foodcritic") : []
end
@tag_cache[cookbook] = tags
tags
end | ruby | def rule_file_tags(file)
cookbook = cookbook_dir(file)
@tag_cache ||= {}
# lookup the tags in the cache has and return that if we find something
cb_tags = @tag_cache[cookbook]
return cb_tags unless cb_tags.nil?
# if a rule file has been specified use that. Otherwise use the .foodcritic file in the CB
tags = if @options[:rule_file]
raise "ERROR: Could not find the specified rule file at #{@options[:rule_file]}" unless File.exist?(@options[:rule_file])
parse_rule_file(@options[:rule_file])
else
File.exist?("#{cookbook}/.foodcritic") ? parse_rule_file("#{cookbook}/.foodcritic") : []
end
@tag_cache[cookbook] = tags
tags
end | [
"def",
"rule_file_tags",
"(",
"file",
")",
"cookbook",
"=",
"cookbook_dir",
"(",
"file",
")",
"@tag_cache",
"||=",
"{",
"}",
"# lookup the tags in the cache has and return that if we find something",
"cb_tags",
"=",
"@tag_cache",
"[",
"cookbook",
"]",
"return",
"cb_tags",
"unless",
"cb_tags",
".",
"nil?",
"# if a rule file has been specified use that. Otherwise use the .foodcritic file in the CB",
"tags",
"=",
"if",
"@options",
"[",
":rule_file",
"]",
"raise",
"\"ERROR: Could not find the specified rule file at #{@options[:rule_file]}\"",
"unless",
"File",
".",
"exist?",
"(",
"@options",
"[",
":rule_file",
"]",
")",
"parse_rule_file",
"(",
"@options",
"[",
":rule_file",
"]",
")",
"else",
"File",
".",
"exist?",
"(",
"\"#{cookbook}/.foodcritic\"",
")",
"?",
"parse_rule_file",
"(",
"\"#{cookbook}/.foodcritic\"",
")",
":",
"[",
"]",
"end",
"@tag_cache",
"[",
"cookbook",
"]",
"=",
"tags",
"tags",
"end"
] | given a file in the cookbook lookup all the applicable tag rules defined in rule
files. The rule file is either that specified via CLI or the .foodcritic file
in the cookbook. We cache this information at the cookbook level to prevent looking
up the same thing dozens of times
@param [String] file in the cookbook
@return [Array] array of tag rules | [
"given",
"a",
"file",
"in",
"the",
"cookbook",
"lookup",
"all",
"the",
"applicable",
"tag",
"rules",
"defined",
"in",
"rule",
"files",
".",
"The",
"rule",
"file",
"is",
"either",
"that",
"specified",
"via",
"CLI",
"or",
"the",
".",
"foodcritic",
"file",
"in",
"the",
"cookbook",
".",
"We",
"cache",
"this",
"information",
"at",
"the",
"cookbook",
"level",
"to",
"prevent",
"looking",
"up",
"the",
"same",
"thing",
"dozens",
"of",
"times"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/linter.rb#L209-L227 | train |
Foodcritic/foodcritic | lib/foodcritic/linter.rb | FoodCritic.Linter.parse_rule_file | def parse_rule_file(file)
tags = []
begin
tag_text = File.read file
tags = tag_text.split(/\s/)
rescue
raise "ERROR: Could not read or parse the specified rule file at #{file}"
end
tags
end | ruby | def parse_rule_file(file)
tags = []
begin
tag_text = File.read file
tags = tag_text.split(/\s/)
rescue
raise "ERROR: Could not read or parse the specified rule file at #{file}"
end
tags
end | [
"def",
"parse_rule_file",
"(",
"file",
")",
"tags",
"=",
"[",
"]",
"begin",
"tag_text",
"=",
"File",
".",
"read",
"file",
"tags",
"=",
"tag_text",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
"rescue",
"raise",
"\"ERROR: Could not read or parse the specified rule file at #{file}\"",
"end",
"tags",
"end"
] | given a filename parse any tag rules in that file
@param [String] rule file path
@return [Array] array of tag rules from the file | [
"given",
"a",
"filename",
"parse",
"any",
"tag",
"rules",
"in",
"that",
"file"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/linter.rb#L233-L242 | train |
Foodcritic/foodcritic | lib/foodcritic/linter.rb | FoodCritic.Linter.cookbook_dir | def cookbook_dir(file)
@dir_cache ||= {}
abs_file = File.absolute_path(file)
# lookup the file in the cache has and return that if we find something
cook_val = @dir_cache[abs_file]
return cook_val unless cook_val.nil?
if file =~ /\.erb$/
# split each directory into an item in the array
dir_array = File.dirname(file).split(File::SEPARATOR)
# walk through the array of directories backwards until we hit the templates directory
position = -1
position -= 1 until dir_array[position] == "templates"
# go back 1 more position to get to the cookbook dir
position -= 1
# slice from the start to the cookbook dir and then join it all back to a string
cook_val = dir_array.slice(0..position).join(File::SEPARATOR)
else
# determine the difference to the root of the CB from our file's directory
relative_difference = case File.basename(file)
when "recipe.rb", "attributes.rb", "metadata.rb" then ""
else # everything else is 1 directory up ie. cookbook/recipes/default.rb
".."
end
cook_val = Pathname.new(File.join(File.dirname(file), relative_difference)).cleanpath
end
@dir_cache[abs_file] = cook_val
cook_val
end | ruby | def cookbook_dir(file)
@dir_cache ||= {}
abs_file = File.absolute_path(file)
# lookup the file in the cache has and return that if we find something
cook_val = @dir_cache[abs_file]
return cook_val unless cook_val.nil?
if file =~ /\.erb$/
# split each directory into an item in the array
dir_array = File.dirname(file).split(File::SEPARATOR)
# walk through the array of directories backwards until we hit the templates directory
position = -1
position -= 1 until dir_array[position] == "templates"
# go back 1 more position to get to the cookbook dir
position -= 1
# slice from the start to the cookbook dir and then join it all back to a string
cook_val = dir_array.slice(0..position).join(File::SEPARATOR)
else
# determine the difference to the root of the CB from our file's directory
relative_difference = case File.basename(file)
when "recipe.rb", "attributes.rb", "metadata.rb" then ""
else # everything else is 1 directory up ie. cookbook/recipes/default.rb
".."
end
cook_val = Pathname.new(File.join(File.dirname(file), relative_difference)).cleanpath
end
@dir_cache[abs_file] = cook_val
cook_val
end | [
"def",
"cookbook_dir",
"(",
"file",
")",
"@dir_cache",
"||=",
"{",
"}",
"abs_file",
"=",
"File",
".",
"absolute_path",
"(",
"file",
")",
"# lookup the file in the cache has and return that if we find something",
"cook_val",
"=",
"@dir_cache",
"[",
"abs_file",
"]",
"return",
"cook_val",
"unless",
"cook_val",
".",
"nil?",
"if",
"file",
"=~",
"/",
"\\.",
"/",
"# split each directory into an item in the array",
"dir_array",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
".",
"split",
"(",
"File",
"::",
"SEPARATOR",
")",
"# walk through the array of directories backwards until we hit the templates directory",
"position",
"=",
"-",
"1",
"position",
"-=",
"1",
"until",
"dir_array",
"[",
"position",
"]",
"==",
"\"templates\"",
"# go back 1 more position to get to the cookbook dir",
"position",
"-=",
"1",
"# slice from the start to the cookbook dir and then join it all back to a string",
"cook_val",
"=",
"dir_array",
".",
"slice",
"(",
"0",
"..",
"position",
")",
".",
"join",
"(",
"File",
"::",
"SEPARATOR",
")",
"else",
"# determine the difference to the root of the CB from our file's directory",
"relative_difference",
"=",
"case",
"File",
".",
"basename",
"(",
"file",
")",
"when",
"\"recipe.rb\"",
",",
"\"attributes.rb\"",
",",
"\"metadata.rb\"",
"then",
"\"\"",
"else",
"# everything else is 1 directory up ie. cookbook/recipes/default.rb",
"\"..\"",
"end",
"cook_val",
"=",
"Pathname",
".",
"new",
"(",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"file",
")",
",",
"relative_difference",
")",
")",
".",
"cleanpath",
"end",
"@dir_cache",
"[",
"abs_file",
"]",
"=",
"cook_val",
"cook_val",
"end"
] | provides the path to the cookbook from a file within the cookbook
we cache this data in a hash because this method gets called often
for the same files.
@param [String] file - a file path in the cookbook
@return [String] the path to the cookbook | [
"provides",
"the",
"path",
"to",
"the",
"cookbook",
"from",
"a",
"file",
"within",
"the",
"cookbook",
"we",
"cache",
"this",
"data",
"in",
"a",
"hash",
"because",
"this",
"method",
"gets",
"called",
"often",
"for",
"the",
"same",
"files",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/linter.rb#L256-L290 | train |
Foodcritic/foodcritic | lib/foodcritic/linter.rb | FoodCritic.Linter.files_to_process | def files_to_process(paths)
paths.reject { |type, _| type == :exclude }.map do |path_type, dirs|
dirs.map do |dir|
exclusions = []
unless paths[:exclude].empty?
exclusions = Dir.glob(paths[:exclude].map do |p|
File.join(dir, p, "**/**")
end)
end
if File.directory?(dir)
glob = if path_type == :cookbook
"{metadata.rb,attributes.rb,recipe.rb,{attributes,definitions,libraries,"\
"providers,recipes,resources}/*.rb,templates/**/*.erb}"
else
"*.rb"
end
(Dir.glob(File.join(dir, glob)) +
Dir.glob(File.join(dir, "*/#{glob}")) - exclusions)
else
dir unless exclusions.include?(dir)
end
end.compact.flatten.map do |filename|
{ filename: filename, path_type: path_type }
end
end.flatten
end | ruby | def files_to_process(paths)
paths.reject { |type, _| type == :exclude }.map do |path_type, dirs|
dirs.map do |dir|
exclusions = []
unless paths[:exclude].empty?
exclusions = Dir.glob(paths[:exclude].map do |p|
File.join(dir, p, "**/**")
end)
end
if File.directory?(dir)
glob = if path_type == :cookbook
"{metadata.rb,attributes.rb,recipe.rb,{attributes,definitions,libraries,"\
"providers,recipes,resources}/*.rb,templates/**/*.erb}"
else
"*.rb"
end
(Dir.glob(File.join(dir, glob)) +
Dir.glob(File.join(dir, "*/#{glob}")) - exclusions)
else
dir unless exclusions.include?(dir)
end
end.compact.flatten.map do |filename|
{ filename: filename, path_type: path_type }
end
end.flatten
end | [
"def",
"files_to_process",
"(",
"paths",
")",
"paths",
".",
"reject",
"{",
"|",
"type",
",",
"_",
"|",
"type",
"==",
":exclude",
"}",
".",
"map",
"do",
"|",
"path_type",
",",
"dirs",
"|",
"dirs",
".",
"map",
"do",
"|",
"dir",
"|",
"exclusions",
"=",
"[",
"]",
"unless",
"paths",
"[",
":exclude",
"]",
".",
"empty?",
"exclusions",
"=",
"Dir",
".",
"glob",
"(",
"paths",
"[",
":exclude",
"]",
".",
"map",
"do",
"|",
"p",
"|",
"File",
".",
"join",
"(",
"dir",
",",
"p",
",",
"\"**/**\"",
")",
"end",
")",
"end",
"if",
"File",
".",
"directory?",
"(",
"dir",
")",
"glob",
"=",
"if",
"path_type",
"==",
":cookbook",
"\"{metadata.rb,attributes.rb,recipe.rb,{attributes,definitions,libraries,\"",
"\"providers,recipes,resources}/*.rb,templates/**/*.erb}\"",
"else",
"\"*.rb\"",
"end",
"(",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"dir",
",",
"glob",
")",
")",
"+",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"dir",
",",
"\"*/#{glob}\"",
")",
")",
"-",
"exclusions",
")",
"else",
"dir",
"unless",
"exclusions",
".",
"include?",
"(",
"dir",
")",
"end",
"end",
".",
"compact",
".",
"flatten",
".",
"map",
"do",
"|",
"filename",
"|",
"{",
"filename",
":",
"filename",
",",
"path_type",
":",
"path_type",
"}",
"end",
"end",
".",
"flatten",
"end"
] | Return the files within a cookbook tree that we are interested in trying to match rules against.
@param [Hash] paths - paths of interest: {:exclude=>[], :cookbook=>[], :role=>[], :environment=>[]}
@return [Array] array of hashes for each file {:filename=>"./metadata.rb", :path_type=>:cookbook} | [
"Return",
"the",
"files",
"within",
"a",
"cookbook",
"tree",
"that",
"we",
"are",
"interested",
"in",
"trying",
"to",
"match",
"rules",
"against",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/linter.rb#L311-L339 | train |
Foodcritic/foodcritic | lib/foodcritic/linter.rb | FoodCritic.Linter.matches | def matches(match_method, *params)
return [] unless match_method.respond_to?(:yield)
matches = match_method.yield(*params)
return [] unless matches.respond_to?(:each)
# We convert Nokogiri nodes to matches transparently
matches.map do |m|
if m.respond_to?(:node_name)
match(m)
elsif m.respond_to?(:xpath)
m.to_a.map { |n| match(n) }
else
m
end
end.flatten
end | ruby | def matches(match_method, *params)
return [] unless match_method.respond_to?(:yield)
matches = match_method.yield(*params)
return [] unless matches.respond_to?(:each)
# We convert Nokogiri nodes to matches transparently
matches.map do |m|
if m.respond_to?(:node_name)
match(m)
elsif m.respond_to?(:xpath)
m.to_a.map { |n| match(n) }
else
m
end
end.flatten
end | [
"def",
"matches",
"(",
"match_method",
",",
"*",
"params",
")",
"return",
"[",
"]",
"unless",
"match_method",
".",
"respond_to?",
"(",
":yield",
")",
"matches",
"=",
"match_method",
".",
"yield",
"(",
"params",
")",
"return",
"[",
"]",
"unless",
"matches",
".",
"respond_to?",
"(",
":each",
")",
"# We convert Nokogiri nodes to matches transparently",
"matches",
".",
"map",
"do",
"|",
"m",
"|",
"if",
"m",
".",
"respond_to?",
"(",
":node_name",
")",
"match",
"(",
"m",
")",
"elsif",
"m",
".",
"respond_to?",
"(",
":xpath",
")",
"m",
".",
"to_a",
".",
"map",
"{",
"|",
"n",
"|",
"match",
"(",
"n",
")",
"}",
"else",
"m",
"end",
"end",
".",
"flatten",
"end"
] | Invoke the DSL method with the provided parameters. | [
"Invoke",
"the",
"DSL",
"method",
"with",
"the",
"provided",
"parameters",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/linter.rb#L342-L357 | train |
Foodcritic/foodcritic | lib/foodcritic/chef.rb | FoodCritic.Chef.valid_query? | def valid_query?(query)
raise ArgumentError, "Query cannot be nil or empty" if query.to_s.empty?
# Attempt to create a search query parser
search = FoodCritic::Chef::Search.new
search.create_parser(search.chef_search_grammars)
if search.parser?
search.parser.parse(query.to_s)
else
# If we didn't manage to get a parser then we can't know if the query
# is valid or not.
true
end
end | ruby | def valid_query?(query)
raise ArgumentError, "Query cannot be nil or empty" if query.to_s.empty?
# Attempt to create a search query parser
search = FoodCritic::Chef::Search.new
search.create_parser(search.chef_search_grammars)
if search.parser?
search.parser.parse(query.to_s)
else
# If we didn't manage to get a parser then we can't know if the query
# is valid or not.
true
end
end | [
"def",
"valid_query?",
"(",
"query",
")",
"raise",
"ArgumentError",
",",
"\"Query cannot be nil or empty\"",
"if",
"query",
".",
"to_s",
".",
"empty?",
"# Attempt to create a search query parser",
"search",
"=",
"FoodCritic",
"::",
"Chef",
"::",
"Search",
".",
"new",
"search",
".",
"create_parser",
"(",
"search",
".",
"chef_search_grammars",
")",
"if",
"search",
".",
"parser?",
"search",
".",
"parser",
".",
"parse",
"(",
"query",
".",
"to_s",
")",
"else",
"# If we didn't manage to get a parser then we can't know if the query",
"# is valid or not.",
"true",
"end",
"end"
] | Is this a valid Lucene query? | [
"Is",
"this",
"a",
"valid",
"Lucene",
"query?"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/chef.rb#L25-L39 | train |
Foodcritic/foodcritic | lib/foodcritic/chef.rb | FoodCritic.Chef.load_metadata | def load_metadata
version = if respond_to?(:chef_version)
chef_version
else
Linter::DEFAULT_CHEF_VERSION
end
metadata_path = [version, version.sub(/\.[a-z].*/, ""),
Linter::DEFAULT_CHEF_VERSION].map do |ver|
metadata_path(ver)
end.find { |m| File.exist?(m) }
@dsl_metadata ||= FFI_Yajl::Parser.parse(IO.read(metadata_path),
symbolize_keys: true)
end | ruby | def load_metadata
version = if respond_to?(:chef_version)
chef_version
else
Linter::DEFAULT_CHEF_VERSION
end
metadata_path = [version, version.sub(/\.[a-z].*/, ""),
Linter::DEFAULT_CHEF_VERSION].map do |ver|
metadata_path(ver)
end.find { |m| File.exist?(m) }
@dsl_metadata ||= FFI_Yajl::Parser.parse(IO.read(metadata_path),
symbolize_keys: true)
end | [
"def",
"load_metadata",
"version",
"=",
"if",
"respond_to?",
"(",
":chef_version",
")",
"chef_version",
"else",
"Linter",
"::",
"DEFAULT_CHEF_VERSION",
"end",
"metadata_path",
"=",
"[",
"version",
",",
"version",
".",
"sub",
"(",
"/",
"\\.",
"/",
",",
"\"\"",
")",
",",
"Linter",
"::",
"DEFAULT_CHEF_VERSION",
"]",
".",
"map",
"do",
"|",
"ver",
"|",
"metadata_path",
"(",
"ver",
")",
"end",
".",
"find",
"{",
"|",
"m",
"|",
"File",
".",
"exist?",
"(",
"m",
")",
"}",
"@dsl_metadata",
"||=",
"FFI_Yajl",
"::",
"Parser",
".",
"parse",
"(",
"IO",
".",
"read",
"(",
"metadata_path",
")",
",",
"symbolize_keys",
":",
"true",
")",
"end"
] | To avoid the runtime hit of loading the Chef gem and its dependencies
we load the DSL metadata from a JSON file shipped with our gem.
The DSL metadata doesn't necessarily reflect the version of Chef in the
local user gemset. | [
"To",
"avoid",
"the",
"runtime",
"hit",
"of",
"loading",
"the",
"Chef",
"gem",
"and",
"its",
"dependencies",
"we",
"load",
"the",
"DSL",
"metadata",
"from",
"a",
"JSON",
"file",
"shipped",
"with",
"our",
"gem",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/chef.rb#L48-L60 | train |
Foodcritic/foodcritic | lib/foodcritic/output.rb | FoodCritic.ContextOutput.output | def output(review)
unless review.respond_to?(:warnings)
puts review; return
end
context = 3
print_fn = lambda { |fn| ansi_print(fn, :red, nil, :bold) }
print_rule = lambda { |warn| ansi_print(warn, :cyan, nil, :bold) }
print_line = lambda { |line| ansi_print(line, nil, :red, :bold) }
key_by_file_and_line(review).each do |fn, warnings|
print_fn.call fn
unless File.exist?(fn)
print_rule.call warnings[1].to_a.join("\n")
next
end
# Set of line numbers with warnings
warn_lines = warnings.keys.to_set
# Moving set of line numbers within the context of our position
context_set = (0..context).to_set
# The last line number we printed a warning for
last_warn = -1
File.open(fn) do |file|
file.each do |line|
context_set.add(file.lineno + context)
context_set.delete(file.lineno - context - 1)
# Find the first warning within our context
context_warns = context_set & warn_lines
next_warn = context_warns.min
# We may need to interrupt the trailing context
# of a previous warning
next_warn = file.lineno if warn_lines.include? file.lineno
# Display a warning
if next_warn && next_warn > last_warn
print_rule.call warnings[next_warn].to_a.join("\n")
last_warn = next_warn
end
# Display any relevant lines
if warn_lines.include? file.lineno
print "%4i|" % file.lineno
print_line.call line.chomp
elsif not context_warns.empty?
print "%4i|" % file.lineno
puts line.chomp
end
end
end
end
end | ruby | def output(review)
unless review.respond_to?(:warnings)
puts review; return
end
context = 3
print_fn = lambda { |fn| ansi_print(fn, :red, nil, :bold) }
print_rule = lambda { |warn| ansi_print(warn, :cyan, nil, :bold) }
print_line = lambda { |line| ansi_print(line, nil, :red, :bold) }
key_by_file_and_line(review).each do |fn, warnings|
print_fn.call fn
unless File.exist?(fn)
print_rule.call warnings[1].to_a.join("\n")
next
end
# Set of line numbers with warnings
warn_lines = warnings.keys.to_set
# Moving set of line numbers within the context of our position
context_set = (0..context).to_set
# The last line number we printed a warning for
last_warn = -1
File.open(fn) do |file|
file.each do |line|
context_set.add(file.lineno + context)
context_set.delete(file.lineno - context - 1)
# Find the first warning within our context
context_warns = context_set & warn_lines
next_warn = context_warns.min
# We may need to interrupt the trailing context
# of a previous warning
next_warn = file.lineno if warn_lines.include? file.lineno
# Display a warning
if next_warn && next_warn > last_warn
print_rule.call warnings[next_warn].to_a.join("\n")
last_warn = next_warn
end
# Display any relevant lines
if warn_lines.include? file.lineno
print "%4i|" % file.lineno
print_line.call line.chomp
elsif not context_warns.empty?
print "%4i|" % file.lineno
puts line.chomp
end
end
end
end
end | [
"def",
"output",
"(",
"review",
")",
"unless",
"review",
".",
"respond_to?",
"(",
":warnings",
")",
"puts",
"review",
";",
"return",
"end",
"context",
"=",
"3",
"print_fn",
"=",
"lambda",
"{",
"|",
"fn",
"|",
"ansi_print",
"(",
"fn",
",",
":red",
",",
"nil",
",",
":bold",
")",
"}",
"print_rule",
"=",
"lambda",
"{",
"|",
"warn",
"|",
"ansi_print",
"(",
"warn",
",",
":cyan",
",",
"nil",
",",
":bold",
")",
"}",
"print_line",
"=",
"lambda",
"{",
"|",
"line",
"|",
"ansi_print",
"(",
"line",
",",
"nil",
",",
":red",
",",
":bold",
")",
"}",
"key_by_file_and_line",
"(",
"review",
")",
".",
"each",
"do",
"|",
"fn",
",",
"warnings",
"|",
"print_fn",
".",
"call",
"fn",
"unless",
"File",
".",
"exist?",
"(",
"fn",
")",
"print_rule",
".",
"call",
"warnings",
"[",
"1",
"]",
".",
"to_a",
".",
"join",
"(",
"\"\\n\"",
")",
"next",
"end",
"# Set of line numbers with warnings",
"warn_lines",
"=",
"warnings",
".",
"keys",
".",
"to_set",
"# Moving set of line numbers within the context of our position",
"context_set",
"=",
"(",
"0",
"..",
"context",
")",
".",
"to_set",
"# The last line number we printed a warning for",
"last_warn",
"=",
"-",
"1",
"File",
".",
"open",
"(",
"fn",
")",
"do",
"|",
"file",
"|",
"file",
".",
"each",
"do",
"|",
"line",
"|",
"context_set",
".",
"add",
"(",
"file",
".",
"lineno",
"+",
"context",
")",
"context_set",
".",
"delete",
"(",
"file",
".",
"lineno",
"-",
"context",
"-",
"1",
")",
"# Find the first warning within our context",
"context_warns",
"=",
"context_set",
"&",
"warn_lines",
"next_warn",
"=",
"context_warns",
".",
"min",
"# We may need to interrupt the trailing context",
"# of a previous warning",
"next_warn",
"=",
"file",
".",
"lineno",
"if",
"warn_lines",
".",
"include?",
"file",
".",
"lineno",
"# Display a warning",
"if",
"next_warn",
"&&",
"next_warn",
">",
"last_warn",
"print_rule",
".",
"call",
"warnings",
"[",
"next_warn",
"]",
".",
"to_a",
".",
"join",
"(",
"\"\\n\"",
")",
"last_warn",
"=",
"next_warn",
"end",
"# Display any relevant lines",
"if",
"warn_lines",
".",
"include?",
"file",
".",
"lineno",
"print",
"\"%4i|\"",
"%",
"file",
".",
"lineno",
"print_line",
".",
"call",
"line",
".",
"chomp",
"elsif",
"not",
"context_warns",
".",
"empty?",
"print",
"\"%4i|\"",
"%",
"file",
".",
"lineno",
"puts",
"line",
".",
"chomp",
"end",
"end",
"end",
"end",
"end"
] | Output the review showing matching lines with context.
@param [Review] review The review to output. | [
"Output",
"the",
"review",
"showing",
"matching",
"lines",
"with",
"context",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/output.rb#L34-L88 | train |
Foodcritic/foodcritic | lib/foodcritic/output.rb | FoodCritic.ContextOutput.key_by_file_and_line | def key_by_file_and_line(review)
warn_hash = {}
review.warnings.each do |warning|
filename = Pathname.new(warning.match[:filename]).cleanpath.to_s
line_num = warning.match[:line].to_i
warn_hash[filename] = {} unless warn_hash.key?(filename)
unless warn_hash[filename].key?(line_num)
warn_hash[filename][line_num] = Set.new
end
warn_hash[filename][line_num] << warning.rule
end
warn_hash
end | ruby | def key_by_file_and_line(review)
warn_hash = {}
review.warnings.each do |warning|
filename = Pathname.new(warning.match[:filename]).cleanpath.to_s
line_num = warning.match[:line].to_i
warn_hash[filename] = {} unless warn_hash.key?(filename)
unless warn_hash[filename].key?(line_num)
warn_hash[filename][line_num] = Set.new
end
warn_hash[filename][line_num] << warning.rule
end
warn_hash
end | [
"def",
"key_by_file_and_line",
"(",
"review",
")",
"warn_hash",
"=",
"{",
"}",
"review",
".",
"warnings",
".",
"each",
"do",
"|",
"warning",
"|",
"filename",
"=",
"Pathname",
".",
"new",
"(",
"warning",
".",
"match",
"[",
":filename",
"]",
")",
".",
"cleanpath",
".",
"to_s",
"line_num",
"=",
"warning",
".",
"match",
"[",
":line",
"]",
".",
"to_i",
"warn_hash",
"[",
"filename",
"]",
"=",
"{",
"}",
"unless",
"warn_hash",
".",
"key?",
"(",
"filename",
")",
"unless",
"warn_hash",
"[",
"filename",
"]",
".",
"key?",
"(",
"line_num",
")",
"warn_hash",
"[",
"filename",
"]",
"[",
"line_num",
"]",
"=",
"Set",
".",
"new",
"end",
"warn_hash",
"[",
"filename",
"]",
"[",
"line_num",
"]",
"<<",
"warning",
".",
"rule",
"end",
"warn_hash",
"end"
] | Build a hash lookup by filename and line number for warnings found in the
specified review.
@param [Review] review The review to convert.
@return [Hash] Nested hashes keyed by filename and line number. | [
"Build",
"a",
"hash",
"lookup",
"by",
"filename",
"and",
"line",
"number",
"for",
"warnings",
"found",
"in",
"the",
"specified",
"review",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/output.rb#L97-L109 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.ensure_file_exists | def ensure_file_exists(basepath, filepath)
path = File.join(basepath, filepath)
[file_match(path)] unless File.exist?(path)
end | ruby | def ensure_file_exists(basepath, filepath)
path = File.join(basepath, filepath)
[file_match(path)] unless File.exist?(path)
end | [
"def",
"ensure_file_exists",
"(",
"basepath",
",",
"filepath",
")",
"path",
"=",
"File",
".",
"join",
"(",
"basepath",
",",
"filepath",
")",
"[",
"file_match",
"(",
"path",
")",
"]",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"end"
] | Match unless a file exists using the basepath of the cookbook and the filepath
@author Joseph Holsten - [email protected]
@since 10.3
@param basepath [String] base path of the cookbook
@param filepath [String] path to the file within the cookbook
@return [String] the absolute path to the base of the cookbook | [
"Match",
"unless",
"a",
"file",
"exists",
"using",
"the",
"basepath",
"of",
"the",
"cookbook",
"and",
"the",
"filepath"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L22-L25 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.attribute_access | def attribute_access(ast, options = {})
options = { type: :any, ignore_calls: false }.merge!(options)
return [] unless ast.respond_to?(:xpath)
unless [:any, :string, :symbol, :vivified].include?(options[:type])
raise ArgumentError, "Node type not recognised"
end
case options[:type]
when :any then
vivified_attribute_access(ast, options) +
standard_attribute_access(ast, options)
when :vivified then
vivified_attribute_access(ast, options)
else
standard_attribute_access(ast, options)
end
end | ruby | def attribute_access(ast, options = {})
options = { type: :any, ignore_calls: false }.merge!(options)
return [] unless ast.respond_to?(:xpath)
unless [:any, :string, :symbol, :vivified].include?(options[:type])
raise ArgumentError, "Node type not recognised"
end
case options[:type]
when :any then
vivified_attribute_access(ast, options) +
standard_attribute_access(ast, options)
when :vivified then
vivified_attribute_access(ast, options)
else
standard_attribute_access(ast, options)
end
end | [
"def",
"attribute_access",
"(",
"ast",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"type",
":",
":any",
",",
"ignore_calls",
":",
"false",
"}",
".",
"merge!",
"(",
"options",
")",
"return",
"[",
"]",
"unless",
"ast",
".",
"respond_to?",
"(",
":xpath",
")",
"unless",
"[",
":any",
",",
":string",
",",
":symbol",
",",
":vivified",
"]",
".",
"include?",
"(",
"options",
"[",
":type",
"]",
")",
"raise",
"ArgumentError",
",",
"\"Node type not recognised\"",
"end",
"case",
"options",
"[",
":type",
"]",
"when",
":any",
"then",
"vivified_attribute_access",
"(",
"ast",
",",
"options",
")",
"+",
"standard_attribute_access",
"(",
"ast",
",",
"options",
")",
"when",
":vivified",
"then",
"vivified_attribute_access",
"(",
"ast",
",",
"options",
")",
"else",
"standard_attribute_access",
"(",
"ast",
",",
"options",
")",
"end",
"end"
] | Find attribute access by type. | [
"Find",
"attribute",
"access",
"by",
"type",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L28-L45 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.cookbook_base_path | def cookbook_base_path(file)
file = File.expand_path(file) # make sure we get an absolute path
file = File.dirname(file) unless File.directory?(file) # get the dir only
# get list of items in the dir and intersect with metadata array.
# until we get an interfact (we have a metadata) walk up the dir structure
until (Dir.entries(file) & %w{metadata.rb metadata.json}).any?
file = File.dirname(file)
end
file
end | ruby | def cookbook_base_path(file)
file = File.expand_path(file) # make sure we get an absolute path
file = File.dirname(file) unless File.directory?(file) # get the dir only
# get list of items in the dir and intersect with metadata array.
# until we get an interfact (we have a metadata) walk up the dir structure
until (Dir.entries(file) & %w{metadata.rb metadata.json}).any?
file = File.dirname(file)
end
file
end | [
"def",
"cookbook_base_path",
"(",
"file",
")",
"file",
"=",
"File",
".",
"expand_path",
"(",
"file",
")",
"# make sure we get an absolute path",
"file",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
"unless",
"File",
".",
"directory?",
"(",
"file",
")",
"# get the dir only",
"# get list of items in the dir and intersect with metadata array.",
"# until we get an interfact (we have a metadata) walk up the dir structure",
"until",
"(",
"Dir",
".",
"entries",
"(",
"file",
")",
"&",
"%w{",
"metadata.rb",
"metadata.json",
"}",
")",
".",
"any?",
"file",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
"end",
"file",
"end"
] | The absolute path of a cookbook from the specified file.
@author Tim Smith - [email protected]
@since 10.1
@param file [String, Pathname] relative or absolute path to a file in the cookbook
@return [String] the absolute path to the base of the cookbook | [
"The",
"absolute",
"path",
"of",
"a",
"cookbook",
"from",
"the",
"specified",
"file",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L53-L64 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.metadata_field | def metadata_field(file, field)
until (file.split(File::SEPARATOR) & standard_cookbook_subdirs).empty?
file = File.absolute_path(File.dirname(file.to_s))
end
file = File.dirname(file) unless File.extname(file).empty?
md_path = File.join(file, "metadata.rb")
if File.exist?(md_path)
value = read_ast(md_path).xpath("//stmts_add/
command[ident/@value='#{field}']/
descendant::tstring_content/@value").to_s
raise "Cant read #{field} from #{md_path}" if value.to_s.empty?
return value
else
raise "Cant find #{md_path}"
end
end | ruby | def metadata_field(file, field)
until (file.split(File::SEPARATOR) & standard_cookbook_subdirs).empty?
file = File.absolute_path(File.dirname(file.to_s))
end
file = File.dirname(file) unless File.extname(file).empty?
md_path = File.join(file, "metadata.rb")
if File.exist?(md_path)
value = read_ast(md_path).xpath("//stmts_add/
command[ident/@value='#{field}']/
descendant::tstring_content/@value").to_s
raise "Cant read #{field} from #{md_path}" if value.to_s.empty?
return value
else
raise "Cant find #{md_path}"
end
end | [
"def",
"metadata_field",
"(",
"file",
",",
"field",
")",
"until",
"(",
"file",
".",
"split",
"(",
"File",
"::",
"SEPARATOR",
")",
"&",
"standard_cookbook_subdirs",
")",
".",
"empty?",
"file",
"=",
"File",
".",
"absolute_path",
"(",
"File",
".",
"dirname",
"(",
"file",
".",
"to_s",
")",
")",
"end",
"file",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
"unless",
"File",
".",
"extname",
"(",
"file",
")",
".",
"empty?",
"md_path",
"=",
"File",
".",
"join",
"(",
"file",
",",
"\"metadata.rb\"",
")",
"if",
"File",
".",
"exist?",
"(",
"md_path",
")",
"value",
"=",
"read_ast",
"(",
"md_path",
")",
".",
"xpath",
"(",
"\"//stmts_add/\n command[ident/@value='#{field}']/\n descendant::tstring_content/@value\"",
")",
".",
"to_s",
"raise",
"\"Cant read #{field} from #{md_path}\"",
"if",
"value",
".",
"to_s",
".",
"empty?",
"return",
"value",
"else",
"raise",
"\"Cant find #{md_path}\"",
"end",
"end"
] | Retrieves a value of a metadata field.
@author Miguel Fonseca
@since 7.0.0
@return [String] the value of the metadata field | [
"Retrieves",
"a",
"value",
"of",
"a",
"metadata",
"field",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L71-L87 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.cookbook_name | def cookbook_name(file)
raise ArgumentError, "File cannot be nil or empty" if file.to_s.empty?
# Name is a special case as we want to fallback to the cookbook directory
# name if metadata_field fails
begin
metadata_field(file, "name")
rescue RuntimeError
until (file.split(File::SEPARATOR) & standard_cookbook_subdirs).empty?
file = File.absolute_path(File.dirname(file.to_s))
end
file = File.dirname(file) unless File.extname(file).empty?
File.basename(file)
end
end | ruby | def cookbook_name(file)
raise ArgumentError, "File cannot be nil or empty" if file.to_s.empty?
# Name is a special case as we want to fallback to the cookbook directory
# name if metadata_field fails
begin
metadata_field(file, "name")
rescue RuntimeError
until (file.split(File::SEPARATOR) & standard_cookbook_subdirs).empty?
file = File.absolute_path(File.dirname(file.to_s))
end
file = File.dirname(file) unless File.extname(file).empty?
File.basename(file)
end
end | [
"def",
"cookbook_name",
"(",
"file",
")",
"raise",
"ArgumentError",
",",
"\"File cannot be nil or empty\"",
"if",
"file",
".",
"to_s",
".",
"empty?",
"# Name is a special case as we want to fallback to the cookbook directory",
"# name if metadata_field fails",
"begin",
"metadata_field",
"(",
"file",
",",
"\"name\"",
")",
"rescue",
"RuntimeError",
"until",
"(",
"file",
".",
"split",
"(",
"File",
"::",
"SEPARATOR",
")",
"&",
"standard_cookbook_subdirs",
")",
".",
"empty?",
"file",
"=",
"File",
".",
"absolute_path",
"(",
"File",
".",
"dirname",
"(",
"file",
".",
"to_s",
")",
")",
"end",
"file",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
"unless",
"File",
".",
"extname",
"(",
"file",
")",
".",
"empty?",
"File",
".",
"basename",
"(",
"file",
")",
"end",
"end"
] | The name of the cookbook containing the specified file.
@param file [String] file within a cookbook
@return [String] name of the cookbook | [
"The",
"name",
"of",
"the",
"cookbook",
"containing",
"the",
"specified",
"file",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L93-L107 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.declared_dependencies | def declared_dependencies(ast)
raise_unless_xpath!(ast)
deps = []
# String literals.
#
# depends 'foo'
deps += field(ast, "depends").xpath("descendant::args_add/descendant::tstring_content[1]")
# Quoted word arrays are also common.
#
# %w{foo bar baz}.each do |cbk|
# depends cbk
# end
deps += word_list_values(field(ast, "depends"))
deps.uniq!
deps.map! { |dep| dep["value"].strip }
deps
end | ruby | def declared_dependencies(ast)
raise_unless_xpath!(ast)
deps = []
# String literals.
#
# depends 'foo'
deps += field(ast, "depends").xpath("descendant::args_add/descendant::tstring_content[1]")
# Quoted word arrays are also common.
#
# %w{foo bar baz}.each do |cbk|
# depends cbk
# end
deps += word_list_values(field(ast, "depends"))
deps.uniq!
deps.map! { |dep| dep["value"].strip }
deps
end | [
"def",
"declared_dependencies",
"(",
"ast",
")",
"raise_unless_xpath!",
"(",
"ast",
")",
"deps",
"=",
"[",
"]",
"# String literals.",
"#",
"# depends 'foo'",
"deps",
"+=",
"field",
"(",
"ast",
",",
"\"depends\"",
")",
".",
"xpath",
"(",
"\"descendant::args_add/descendant::tstring_content[1]\"",
")",
"# Quoted word arrays are also common.",
"#",
"# %w{foo bar baz}.each do |cbk|",
"# depends cbk",
"# end",
"deps",
"+=",
"word_list_values",
"(",
"field",
"(",
"ast",
",",
"\"depends\"",
")",
")",
"deps",
".",
"uniq!",
"deps",
".",
"map!",
"{",
"|",
"dep",
"|",
"dep",
"[",
"\"value\"",
"]",
".",
"strip",
"}",
"deps",
"end"
] | The dependencies declared in cookbook metadata. | [
"The",
"dependencies",
"declared",
"in",
"cookbook",
"metadata",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L130-L148 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.field | def field(ast, field_name)
if field_name.nil? || field_name.to_s.empty?
raise ArgumentError, "Field name cannot be nil or empty"
end
ast.xpath("(.//command[ident/@value='#{field_name}']|.//fcall[ident/@value='#{field_name}']/..)")
end | ruby | def field(ast, field_name)
if field_name.nil? || field_name.to_s.empty?
raise ArgumentError, "Field name cannot be nil or empty"
end
ast.xpath("(.//command[ident/@value='#{field_name}']|.//fcall[ident/@value='#{field_name}']/..)")
end | [
"def",
"field",
"(",
"ast",
",",
"field_name",
")",
"if",
"field_name",
".",
"nil?",
"||",
"field_name",
".",
"to_s",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"Field name cannot be nil or empty\"",
"end",
"ast",
".",
"xpath",
"(",
"\"(.//command[ident/@value='#{field_name}']|.//fcall[ident/@value='#{field_name}']/..)\"",
")",
"end"
] | Look for a method call with a given name.
@param ast [Nokogiri::XML::Node] Document to search under
@param field_name [String] Method name to search for
@return [Nokogiri::XML::NodeSet] | [
"Look",
"for",
"a",
"method",
"call",
"with",
"a",
"given",
"name",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L155-L160 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.field_value | def field_value(ast, field_name)
field(ast, field_name).xpath('.//args_add_block//tstring_content
[count(ancestor::args_add) = 1][count(ancestor::string_add) = 1]
/@value').map { |a| a.to_s }.last
end | ruby | def field_value(ast, field_name)
field(ast, field_name).xpath('.//args_add_block//tstring_content
[count(ancestor::args_add) = 1][count(ancestor::string_add) = 1]
/@value').map { |a| a.to_s }.last
end | [
"def",
"field_value",
"(",
"ast",
",",
"field_name",
")",
"field",
"(",
"ast",
",",
"field_name",
")",
".",
"xpath",
"(",
"'.//args_add_block//tstring_content\n [count(ancestor::args_add) = 1][count(ancestor::string_add) = 1]\n /@value'",
")",
".",
"map",
"{",
"|",
"a",
"|",
"a",
".",
"to_s",
"}",
".",
"last",
"end"
] | The value for a specific key in an environment or role ruby file | [
"The",
"value",
"for",
"a",
"specific",
"key",
"in",
"an",
"environment",
"or",
"role",
"ruby",
"file"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L163-L167 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.file_match | def file_match(file)
raise ArgumentError, "Filename cannot be nil" if file.nil?
{ filename: file, matched: file, line: 1, column: 1 }
end | ruby | def file_match(file)
raise ArgumentError, "Filename cannot be nil" if file.nil?
{ filename: file, matched: file, line: 1, column: 1 }
end | [
"def",
"file_match",
"(",
"file",
")",
"raise",
"ArgumentError",
",",
"\"Filename cannot be nil\"",
"if",
"file",
".",
"nil?",
"{",
"filename",
":",
"file",
",",
"matched",
":",
"file",
",",
"line",
":",
"1",
",",
"column",
":",
"1",
"}",
"end"
] | Create a match for a specified file. Use this if the presence of the file
triggers the warning rather than content. | [
"Create",
"a",
"match",
"for",
"a",
"specified",
"file",
".",
"Use",
"this",
"if",
"the",
"presence",
"of",
"the",
"file",
"triggers",
"the",
"warning",
"rather",
"than",
"content",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L171-L174 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.included_recipes | def included_recipes(ast, options = { with_partial_names: true })
raise_unless_xpath!(ast)
filter = ["[count(descendant::args_add) = 1]"]
# If `:with_partial_names` is false then we won't include the string
# literal portions of any string that has an embedded expression.
unless options[:with_partial_names]
filter << "[count(descendant::string_embexpr) = 0]"
end
string_desc = '[descendant::args_add/string_literal]/
descendant::tstring_content'
included = ast.xpath([
"//command[ident/@value = 'include_recipe']",
"//fcall[ident/@value = 'include_recipe']/
following-sibling::arg_paren",
].map do |recipe_include|
recipe_include + filter.join + string_desc
end.join(" | "))
# Hash keyed by recipe name with matched nodes.
included.inject(Hash.new([])) { |h, i| h[i["value"]] += [i]; h }
end | ruby | def included_recipes(ast, options = { with_partial_names: true })
raise_unless_xpath!(ast)
filter = ["[count(descendant::args_add) = 1]"]
# If `:with_partial_names` is false then we won't include the string
# literal portions of any string that has an embedded expression.
unless options[:with_partial_names]
filter << "[count(descendant::string_embexpr) = 0]"
end
string_desc = '[descendant::args_add/string_literal]/
descendant::tstring_content'
included = ast.xpath([
"//command[ident/@value = 'include_recipe']",
"//fcall[ident/@value = 'include_recipe']/
following-sibling::arg_paren",
].map do |recipe_include|
recipe_include + filter.join + string_desc
end.join(" | "))
# Hash keyed by recipe name with matched nodes.
included.inject(Hash.new([])) { |h, i| h[i["value"]] += [i]; h }
end | [
"def",
"included_recipes",
"(",
"ast",
",",
"options",
"=",
"{",
"with_partial_names",
":",
"true",
"}",
")",
"raise_unless_xpath!",
"(",
"ast",
")",
"filter",
"=",
"[",
"\"[count(descendant::args_add) = 1]\"",
"]",
"# If `:with_partial_names` is false then we won't include the string",
"# literal portions of any string that has an embedded expression.",
"unless",
"options",
"[",
":with_partial_names",
"]",
"filter",
"<<",
"\"[count(descendant::string_embexpr) = 0]\"",
"end",
"string_desc",
"=",
"'[descendant::args_add/string_literal]/\n descendant::tstring_content'",
"included",
"=",
"ast",
".",
"xpath",
"(",
"[",
"\"//command[ident/@value = 'include_recipe']\"",
",",
"\"//fcall[ident/@value = 'include_recipe']/\n following-sibling::arg_paren\"",
",",
"]",
".",
"map",
"do",
"|",
"recipe_include",
"|",
"recipe_include",
"+",
"filter",
".",
"join",
"+",
"string_desc",
"end",
".",
"join",
"(",
"\" | \"",
")",
")",
"# Hash keyed by recipe name with matched nodes.",
"included",
".",
"inject",
"(",
"Hash",
".",
"new",
"(",
"[",
"]",
")",
")",
"{",
"|",
"h",
",",
"i",
"|",
"h",
"[",
"i",
"[",
"\"value\"",
"]",
"]",
"+=",
"[",
"i",
"]",
";",
"h",
"}",
"end"
] | Retrieve the recipes that are included within the given recipe AST.
These two usages are equivalent:
included_recipes(ast)
included_recipes(ast, :with_partial_names => true) | [
"Retrieve",
"the",
"recipes",
"that",
"are",
"included",
"within",
"the",
"given",
"recipe",
"AST",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L215-L238 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.match | def match(node)
raise_unless_xpath!(node)
pos = node.xpath("descendant::pos").first
return nil if pos.nil?
{ matched: node.respond_to?(:name) ? node.name : "",
line: pos["line"].to_i, column: pos["column"].to_i }
end | ruby | def match(node)
raise_unless_xpath!(node)
pos = node.xpath("descendant::pos").first
return nil if pos.nil?
{ matched: node.respond_to?(:name) ? node.name : "",
line: pos["line"].to_i, column: pos["column"].to_i }
end | [
"def",
"match",
"(",
"node",
")",
"raise_unless_xpath!",
"(",
"node",
")",
"pos",
"=",
"node",
".",
"xpath",
"(",
"\"descendant::pos\"",
")",
".",
"first",
"return",
"nil",
"if",
"pos",
".",
"nil?",
"{",
"matched",
":",
"node",
".",
"respond_to?",
"(",
":name",
")",
"?",
"node",
".",
"name",
":",
"\"\"",
",",
"line",
":",
"pos",
"[",
"\"line\"",
"]",
".",
"to_i",
",",
"column",
":",
"pos",
"[",
"\"column\"",
"]",
".",
"to_i",
"}",
"end"
] | Create a match from the specified node. | [
"Create",
"a",
"match",
"from",
"the",
"specified",
"node",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L249-L255 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.read_ast | def read_ast(file)
@ast_cache ||= Rufus::Lru::Hash.new(5)
if @ast_cache.include?(file)
@ast_cache[file]
else
@ast_cache[file] = uncached_read_ast(file)
end
end | ruby | def read_ast(file)
@ast_cache ||= Rufus::Lru::Hash.new(5)
if @ast_cache.include?(file)
@ast_cache[file]
else
@ast_cache[file] = uncached_read_ast(file)
end
end | [
"def",
"read_ast",
"(",
"file",
")",
"@ast_cache",
"||=",
"Rufus",
"::",
"Lru",
"::",
"Hash",
".",
"new",
"(",
"5",
")",
"if",
"@ast_cache",
".",
"include?",
"(",
"file",
")",
"@ast_cache",
"[",
"file",
"]",
"else",
"@ast_cache",
"[",
"file",
"]",
"=",
"uncached_read_ast",
"(",
"file",
")",
"end",
"end"
] | Read the AST for the given Ruby source file | [
"Read",
"the",
"AST",
"for",
"the",
"given",
"Ruby",
"source",
"file"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L258-L265 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.resource_attribute | def resource_attribute(resource, name)
raise ArgumentError, "Attribute name cannot be empty" if name.empty?
resource_attributes(resource)[name.to_s]
end | ruby | def resource_attribute(resource, name)
raise ArgumentError, "Attribute name cannot be empty" if name.empty?
resource_attributes(resource)[name.to_s]
end | [
"def",
"resource_attribute",
"(",
"resource",
",",
"name",
")",
"raise",
"ArgumentError",
",",
"\"Attribute name cannot be empty\"",
"if",
"name",
".",
"empty?",
"resource_attributes",
"(",
"resource",
")",
"[",
"name",
".",
"to_s",
"]",
"end"
] | Retrieve a single-valued attribute from the specified resource. | [
"Retrieve",
"a",
"single",
"-",
"valued",
"attribute",
"from",
"the",
"specified",
"resource",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L268-L271 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.resource_attributes | def resource_attributes(resource, options = {})
atts = {}
name = resource_name(resource, options)
atts[:name] = name unless name.empty?
atts.merge!(normal_attributes(resource, options))
atts.merge!(block_attributes(resource))
atts
end | ruby | def resource_attributes(resource, options = {})
atts = {}
name = resource_name(resource, options)
atts[:name] = name unless name.empty?
atts.merge!(normal_attributes(resource, options))
atts.merge!(block_attributes(resource))
atts
end | [
"def",
"resource_attributes",
"(",
"resource",
",",
"options",
"=",
"{",
"}",
")",
"atts",
"=",
"{",
"}",
"name",
"=",
"resource_name",
"(",
"resource",
",",
"options",
")",
"atts",
"[",
":name",
"]",
"=",
"name",
"unless",
"name",
".",
"empty?",
"atts",
".",
"merge!",
"(",
"normal_attributes",
"(",
"resource",
",",
"options",
")",
")",
"atts",
".",
"merge!",
"(",
"block_attributes",
"(",
"resource",
")",
")",
"atts",
"end"
] | Retrieve all attributes from the specified resource. | [
"Retrieve",
"all",
"attributes",
"from",
"the",
"specified",
"resource",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L274-L281 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.resource_attributes_by_type | def resource_attributes_by_type(ast)
result = {}
resources_by_type(ast).each do |type, resources|
result[type] = resources.map do |resource|
resource_attributes(resource)
end
end
result
end | ruby | def resource_attributes_by_type(ast)
result = {}
resources_by_type(ast).each do |type, resources|
result[type] = resources.map do |resource|
resource_attributes(resource)
end
end
result
end | [
"def",
"resource_attributes_by_type",
"(",
"ast",
")",
"result",
"=",
"{",
"}",
"resources_by_type",
"(",
"ast",
")",
".",
"each",
"do",
"|",
"type",
",",
"resources",
"|",
"result",
"[",
"type",
"]",
"=",
"resources",
".",
"map",
"do",
"|",
"resource",
"|",
"resource_attributes",
"(",
"resource",
")",
"end",
"end",
"result",
"end"
] | Resources keyed by type, with an array of matching nodes for each. | [
"Resources",
"keyed",
"by",
"type",
"with",
"an",
"array",
"of",
"matching",
"nodes",
"for",
"each",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L284-L292 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.resource_name | def resource_name(resource, options = {})
raise_unless_xpath!(resource)
options = { return_expressions: false }.merge(options)
if options[:return_expressions]
name = resource.xpath("command/args_add_block")
if name.xpath("descendant::string_add").size == 1 &&
name.xpath("descendant::string_literal").size == 1 &&
name.xpath(
"descendant::*[self::call or self::string_embexpr]").empty?
name.xpath("descendant::tstring_content/@value").to_s
else
name
end
else
# Preserve existing behaviour
resource.xpath("string(command//tstring_content/@value)")
end
end | ruby | def resource_name(resource, options = {})
raise_unless_xpath!(resource)
options = { return_expressions: false }.merge(options)
if options[:return_expressions]
name = resource.xpath("command/args_add_block")
if name.xpath("descendant::string_add").size == 1 &&
name.xpath("descendant::string_literal").size == 1 &&
name.xpath(
"descendant::*[self::call or self::string_embexpr]").empty?
name.xpath("descendant::tstring_content/@value").to_s
else
name
end
else
# Preserve existing behaviour
resource.xpath("string(command//tstring_content/@value)")
end
end | [
"def",
"resource_name",
"(",
"resource",
",",
"options",
"=",
"{",
"}",
")",
"raise_unless_xpath!",
"(",
"resource",
")",
"options",
"=",
"{",
"return_expressions",
":",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"if",
"options",
"[",
":return_expressions",
"]",
"name",
"=",
"resource",
".",
"xpath",
"(",
"\"command/args_add_block\"",
")",
"if",
"name",
".",
"xpath",
"(",
"\"descendant::string_add\"",
")",
".",
"size",
"==",
"1",
"&&",
"name",
".",
"xpath",
"(",
"\"descendant::string_literal\"",
")",
".",
"size",
"==",
"1",
"&&",
"name",
".",
"xpath",
"(",
"\"descendant::*[self::call or self::string_embexpr]\"",
")",
".",
"empty?",
"name",
".",
"xpath",
"(",
"\"descendant::tstring_content/@value\"",
")",
".",
"to_s",
"else",
"name",
"end",
"else",
"# Preserve existing behaviour",
"resource",
".",
"xpath",
"(",
"\"string(command//tstring_content/@value)\"",
")",
"end",
"end"
] | Retrieve the name attribute associated with the specified resource. | [
"Retrieve",
"the",
"name",
"attribute",
"associated",
"with",
"the",
"specified",
"resource",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L295-L312 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.resources_by_type | def resources_by_type(ast)
raise_unless_xpath!(ast)
result = Hash.new { |hash, key| hash[key] = Array.new }
find_resources(ast).each do |resource|
result[resource_type(resource)] << resource
end
result
end | ruby | def resources_by_type(ast)
raise_unless_xpath!(ast)
result = Hash.new { |hash, key| hash[key] = Array.new }
find_resources(ast).each do |resource|
result[resource_type(resource)] << resource
end
result
end | [
"def",
"resources_by_type",
"(",
"ast",
")",
"raise_unless_xpath!",
"(",
"ast",
")",
"result",
"=",
"Hash",
".",
"new",
"{",
"|",
"hash",
",",
"key",
"|",
"hash",
"[",
"key",
"]",
"=",
"Array",
".",
"new",
"}",
"find_resources",
"(",
"ast",
")",
".",
"each",
"do",
"|",
"resource",
"|",
"result",
"[",
"resource_type",
"(",
"resource",
")",
"]",
"<<",
"resource",
"end",
"result",
"end"
] | Resources in an AST, keyed by type. | [
"Resources",
"in",
"an",
"AST",
"keyed",
"by",
"type",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L315-L322 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.ruby_code? | def ruby_code?(str)
str = str.to_s
return false if str.empty?
checker = FoodCritic::ErrorChecker.new(str)
checker.parse
!checker.error?
end | ruby | def ruby_code?(str)
str = str.to_s
return false if str.empty?
checker = FoodCritic::ErrorChecker.new(str)
checker.parse
!checker.error?
end | [
"def",
"ruby_code?",
"(",
"str",
")",
"str",
"=",
"str",
".",
"to_s",
"return",
"false",
"if",
"str",
".",
"empty?",
"checker",
"=",
"FoodCritic",
"::",
"ErrorChecker",
".",
"new",
"(",
"str",
")",
"checker",
".",
"parse",
"!",
"checker",
".",
"error?",
"end"
] | Does the provided string look like ruby code? | [
"Does",
"the",
"provided",
"string",
"look",
"like",
"ruby",
"code?"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L335-L342 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.supported_platforms | def supported_platforms(ast)
# Find the supports() method call.
platforms_ast = field(ast, "supports")
# Look for the first argument (the node next to the top args_new) and
# filter out anything with a string_embexpr since that can't be parsed
# statically. Then grab the static value for both strings and symbols, and
# finally combine it with the word list (%w{}) analyzer.
platforms = platforms_ast.xpath("(.//args_new)[1]/../*[not(.//string_embexpr)]").xpath(".//tstring_content|.//symbol/ident") | word_list_values(platforms_ast)
platforms.map do |platform|
# For each platform value, look for all arguments after the first, then
# extract the string literal value.
versions = platform.xpath("ancestor::args_add[not(args_new)]/*[position()=2]//tstring_content/@value")
{ platform: platform["value"].lstrip, versions: versions.map(&:to_s) }
end.sort_by { |p| p[:platform] }
end | ruby | def supported_platforms(ast)
# Find the supports() method call.
platforms_ast = field(ast, "supports")
# Look for the first argument (the node next to the top args_new) and
# filter out anything with a string_embexpr since that can't be parsed
# statically. Then grab the static value for both strings and symbols, and
# finally combine it with the word list (%w{}) analyzer.
platforms = platforms_ast.xpath("(.//args_new)[1]/../*[not(.//string_embexpr)]").xpath(".//tstring_content|.//symbol/ident") | word_list_values(platforms_ast)
platforms.map do |platform|
# For each platform value, look for all arguments after the first, then
# extract the string literal value.
versions = platform.xpath("ancestor::args_add[not(args_new)]/*[position()=2]//tstring_content/@value")
{ platform: platform["value"].lstrip, versions: versions.map(&:to_s) }
end.sort_by { |p| p[:platform] }
end | [
"def",
"supported_platforms",
"(",
"ast",
")",
"# Find the supports() method call.",
"platforms_ast",
"=",
"field",
"(",
"ast",
",",
"\"supports\"",
")",
"# Look for the first argument (the node next to the top args_new) and",
"# filter out anything with a string_embexpr since that can't be parsed",
"# statically. Then grab the static value for both strings and symbols, and",
"# finally combine it with the word list (%w{}) analyzer.",
"platforms",
"=",
"platforms_ast",
".",
"xpath",
"(",
"\"(.//args_new)[1]/../*[not(.//string_embexpr)]\"",
")",
".",
"xpath",
"(",
"\".//tstring_content|.//symbol/ident\"",
")",
"|",
"word_list_values",
"(",
"platforms_ast",
")",
"platforms",
".",
"map",
"do",
"|",
"platform",
"|",
"# For each platform value, look for all arguments after the first, then",
"# extract the string literal value.",
"versions",
"=",
"platform",
".",
"xpath",
"(",
"\"ancestor::args_add[not(args_new)]/*[position()=2]//tstring_content/@value\"",
")",
"{",
"platform",
":",
"platform",
"[",
"\"value\"",
"]",
".",
"lstrip",
",",
"versions",
":",
"versions",
".",
"map",
"(",
":to_s",
")",
"}",
"end",
".",
"sort_by",
"{",
"|",
"p",
"|",
"p",
"[",
":platform",
"]",
"}",
"end"
] | Platforms declared as supported in cookbook metadata. Returns an array
of hashes containing the name and version constraints for each platform.
@param ast [Nokogiri::XML::Node] Document to search from.
@return [Array<Hash>] | [
"Platforms",
"declared",
"as",
"supported",
"in",
"cookbook",
"metadata",
".",
"Returns",
"an",
"array",
"of",
"hashes",
"containing",
"the",
"name",
"and",
"version",
"constraints",
"for",
"each",
"platform",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L364-L378 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.template_paths | def template_paths(recipe_path)
Dir.glob(Pathname.new(recipe_path).dirname.dirname + "templates" +
"**/*", File::FNM_DOTMATCH).select do |path|
File.file?(path)
end.reject do |path|
File.basename(path) == ".DS_Store" || File.extname(path) == ".swp"
end
end | ruby | def template_paths(recipe_path)
Dir.glob(Pathname.new(recipe_path).dirname.dirname + "templates" +
"**/*", File::FNM_DOTMATCH).select do |path|
File.file?(path)
end.reject do |path|
File.basename(path) == ".DS_Store" || File.extname(path) == ".swp"
end
end | [
"def",
"template_paths",
"(",
"recipe_path",
")",
"Dir",
".",
"glob",
"(",
"Pathname",
".",
"new",
"(",
"recipe_path",
")",
".",
"dirname",
".",
"dirname",
"+",
"\"templates\"",
"+",
"\"**/*\"",
",",
"File",
"::",
"FNM_DOTMATCH",
")",
".",
"select",
"do",
"|",
"path",
"|",
"File",
".",
"file?",
"(",
"path",
")",
"end",
".",
"reject",
"do",
"|",
"path",
"|",
"File",
".",
"basename",
"(",
"path",
")",
"==",
"\".DS_Store\"",
"||",
"File",
".",
"extname",
"(",
"path",
")",
"==",
"\".swp\"",
"end",
"end"
] | Templates in the current cookbook | [
"Templates",
"in",
"the",
"current",
"cookbook"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L410-L417 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.json_file_to_hash | def json_file_to_hash(filename)
raise "File #{filename} not found" unless File.exist?(filename)
file = File.read(filename)
begin
FFI_Yajl::Parser.parse(file)
rescue FFI_Yajl::ParseError
raise "File #{filename} does not appear to contain valid JSON"
end
end | ruby | def json_file_to_hash(filename)
raise "File #{filename} not found" unless File.exist?(filename)
file = File.read(filename)
begin
FFI_Yajl::Parser.parse(file)
rescue FFI_Yajl::ParseError
raise "File #{filename} does not appear to contain valid JSON"
end
end | [
"def",
"json_file_to_hash",
"(",
"filename",
")",
"raise",
"\"File #{filename} not found\"",
"unless",
"File",
".",
"exist?",
"(",
"filename",
")",
"file",
"=",
"File",
".",
"read",
"(",
"filename",
")",
"begin",
"FFI_Yajl",
"::",
"Parser",
".",
"parse",
"(",
"file",
")",
"rescue",
"FFI_Yajl",
"::",
"ParseError",
"raise",
"\"File #{filename} does not appear to contain valid JSON\"",
"end",
"end"
] | Give a filename path it returns the hash of the JSON contents
@author Tim Smith - [email protected]
@since 11.0
@param filename [String] path to a file in JSON format
@return [Hash] hash of JSON content | [
"Give",
"a",
"filename",
"path",
"it",
"returns",
"the",
"hash",
"of",
"the",
"JSON",
"contents"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L425-L434 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.build_xml | def build_xml(node, doc = nil, xml_node = nil)
doc, xml_node = xml_document(doc, xml_node)
if node.respond_to?(:each)
node.each do |child|
if position_node?(child)
xml_position_node(doc, xml_node, child)
else
if ast_node_has_children?(child)
# The AST structure is different for hashes so we have to treat
# them separately.
if ast_hash_node?(child)
xml_hash_node(doc, xml_node, child)
else
xml_array_node(doc, xml_node, child)
end
else
xml_node["value"] = child.to_s unless child.nil?
end
end
end
end
xml_node
end | ruby | def build_xml(node, doc = nil, xml_node = nil)
doc, xml_node = xml_document(doc, xml_node)
if node.respond_to?(:each)
node.each do |child|
if position_node?(child)
xml_position_node(doc, xml_node, child)
else
if ast_node_has_children?(child)
# The AST structure is different for hashes so we have to treat
# them separately.
if ast_hash_node?(child)
xml_hash_node(doc, xml_node, child)
else
xml_array_node(doc, xml_node, child)
end
else
xml_node["value"] = child.to_s unless child.nil?
end
end
end
end
xml_node
end | [
"def",
"build_xml",
"(",
"node",
",",
"doc",
"=",
"nil",
",",
"xml_node",
"=",
"nil",
")",
"doc",
",",
"xml_node",
"=",
"xml_document",
"(",
"doc",
",",
"xml_node",
")",
"if",
"node",
".",
"respond_to?",
"(",
":each",
")",
"node",
".",
"each",
"do",
"|",
"child",
"|",
"if",
"position_node?",
"(",
"child",
")",
"xml_position_node",
"(",
"doc",
",",
"xml_node",
",",
"child",
")",
"else",
"if",
"ast_node_has_children?",
"(",
"child",
")",
"# The AST structure is different for hashes so we have to treat",
"# them separately.",
"if",
"ast_hash_node?",
"(",
"child",
")",
"xml_hash_node",
"(",
"doc",
",",
"xml_node",
",",
"child",
")",
"else",
"xml_array_node",
"(",
"doc",
",",
"xml_node",
",",
"child",
")",
"end",
"else",
"xml_node",
"[",
"\"value\"",
"]",
"=",
"child",
".",
"to_s",
"unless",
"child",
".",
"nil?",
"end",
"end",
"end",
"end",
"xml_node",
"end"
] | Recurse the nested arrays provided by Ripper to create a tree we can more
easily apply expressions to. | [
"Recurse",
"the",
"nested",
"arrays",
"provided",
"by",
"Ripper",
"to",
"create",
"a",
"tree",
"we",
"can",
"more",
"easily",
"apply",
"expressions",
"to",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L458-L481 | train |
Foodcritic/foodcritic | lib/foodcritic/api.rb | FoodCritic.Api.node_method? | def node_method?(meth, cookbook_dir)
chef_dsl_methods.include?(meth) || meth == :set || meth == :set_unless ||
patched_node_method?(meth, cookbook_dir)
end | ruby | def node_method?(meth, cookbook_dir)
chef_dsl_methods.include?(meth) || meth == :set || meth == :set_unless ||
patched_node_method?(meth, cookbook_dir)
end | [
"def",
"node_method?",
"(",
"meth",
",",
"cookbook_dir",
")",
"chef_dsl_methods",
".",
"include?",
"(",
"meth",
")",
"||",
"meth",
"==",
":set",
"||",
"meth",
"==",
":set_unless",
"||",
"patched_node_method?",
"(",
"meth",
",",
"cookbook_dir",
")",
"end"
] | check to see if the passed method is a node method
we generally look this up from the chef DSL data we have
but we specifically check for 'set' and 'set_unless' since
those exist in cookbooks, but are not longer part of chef 14+
this prevents false positives in FC019 anytime node.set is found | [
"check",
"to",
"see",
"if",
"the",
"passed",
"method",
"is",
"a",
"node",
"method",
"we",
"generally",
"look",
"this",
"up",
"from",
"the",
"chef",
"DSL",
"data",
"we",
"have",
"but",
"we",
"specifically",
"check",
"for",
"set",
"and",
"set_unless",
"since",
"those",
"exist",
"in",
"cookbooks",
"but",
"are",
"not",
"longer",
"part",
"of",
"chef",
"14",
"+",
"this",
"prevents",
"false",
"positives",
"in",
"FC019",
"anytime",
"node",
".",
"set",
"is",
"found"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/api.rb#L519-L522 | train |
Foodcritic/foodcritic | features/support/command_helpers.rb | FoodCritic.CommandHelpers.expect_warning | def expect_warning(code, options = {})
if options.has_key?(:file_type)
options[:file] = { :attributes => "attributes/default.rb", :definition => "definitions/apache_site.rb",
:metadata => "metadata.rb", :provider => "providers/site.rb",
:resource => "resources/site.rb", :libraries => "libraries/lib.rb" }[options[:file_type]]
end
options = { :line => 1, :expect_warning => true, :file => "recipes/default.rb" }.merge!(options)
unless options[:file].include?("roles") ||
options[:file].include?("environments")
options[:file] = "cookbooks/example/#{options[:file]}"
end
if options[:warning_only]
warning = "#{code}: #{WARNINGS[code]}"
else
warning = "#{code}: #{WARNINGS[code]}: #{options[:file]}:#{options[:line]}#{"\n" if ! options[:line].nil?}"
end
options[:expect_warning] ? expect_output(warning) : expect_no_output(warning)
end | ruby | def expect_warning(code, options = {})
if options.has_key?(:file_type)
options[:file] = { :attributes => "attributes/default.rb", :definition => "definitions/apache_site.rb",
:metadata => "metadata.rb", :provider => "providers/site.rb",
:resource => "resources/site.rb", :libraries => "libraries/lib.rb" }[options[:file_type]]
end
options = { :line => 1, :expect_warning => true, :file => "recipes/default.rb" }.merge!(options)
unless options[:file].include?("roles") ||
options[:file].include?("environments")
options[:file] = "cookbooks/example/#{options[:file]}"
end
if options[:warning_only]
warning = "#{code}: #{WARNINGS[code]}"
else
warning = "#{code}: #{WARNINGS[code]}: #{options[:file]}:#{options[:line]}#{"\n" if ! options[:line].nil?}"
end
options[:expect_warning] ? expect_output(warning) : expect_no_output(warning)
end | [
"def",
"expect_warning",
"(",
"code",
",",
"options",
"=",
"{",
"}",
")",
"if",
"options",
".",
"has_key?",
"(",
":file_type",
")",
"options",
"[",
":file",
"]",
"=",
"{",
":attributes",
"=>",
"\"attributes/default.rb\"",
",",
":definition",
"=>",
"\"definitions/apache_site.rb\"",
",",
":metadata",
"=>",
"\"metadata.rb\"",
",",
":provider",
"=>",
"\"providers/site.rb\"",
",",
":resource",
"=>",
"\"resources/site.rb\"",
",",
":libraries",
"=>",
"\"libraries/lib.rb\"",
"}",
"[",
"options",
"[",
":file_type",
"]",
"]",
"end",
"options",
"=",
"{",
":line",
"=>",
"1",
",",
":expect_warning",
"=>",
"true",
",",
":file",
"=>",
"\"recipes/default.rb\"",
"}",
".",
"merge!",
"(",
"options",
")",
"unless",
"options",
"[",
":file",
"]",
".",
"include?",
"(",
"\"roles\"",
")",
"||",
"options",
"[",
":file",
"]",
".",
"include?",
"(",
"\"environments\"",
")",
"options",
"[",
":file",
"]",
"=",
"\"cookbooks/example/#{options[:file]}\"",
"end",
"if",
"options",
"[",
":warning_only",
"]",
"warning",
"=",
"\"#{code}: #{WARNINGS[code]}\"",
"else",
"warning",
"=",
"\"#{code}: #{WARNINGS[code]}: #{options[:file]}:#{options[:line]}#{\"\\n\" if ! options[:line].nil?}\"",
"end",
"options",
"[",
":expect_warning",
"]",
"?",
"expect_output",
"(",
"warning",
")",
":",
"expect_no_output",
"(",
"warning",
")",
"end"
] | Expect a warning to be included in the command output.
@param [String] code The warning code to check for.
@param [Hash] options The warning options.
@option options [Integer] :line The line number the warning should appear on - nil for any line.
@option options [Boolean] :expect_warning If false then assert that a warning is NOT present
@option options [String] :file The path to the file the warning should be raised against
@option options [Symbol] :file_type Alternative to specifying file name. One of: :attributes, :definition,
:metadata, :provider, :resource | [
"Expect",
"a",
"warning",
"to",
"be",
"included",
"in",
"the",
"command",
"output",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/command_helpers.rb#L115-L132 | train |
Foodcritic/foodcritic | features/support/command_helpers.rb | FoodCritic.CommandHelpers.usage_displayed | def usage_displayed(is_exit_zero)
expect_output "foodcritic [cookbook_paths]"
usage_options.each do |option|
expect_usage_option(option[:short], option[:long], option[:description])
end
if is_exit_zero
assert_no_error_occurred
else
assert_error_occurred
end
end | ruby | def usage_displayed(is_exit_zero)
expect_output "foodcritic [cookbook_paths]"
usage_options.each do |option|
expect_usage_option(option[:short], option[:long], option[:description])
end
if is_exit_zero
assert_no_error_occurred
else
assert_error_occurred
end
end | [
"def",
"usage_displayed",
"(",
"is_exit_zero",
")",
"expect_output",
"\"foodcritic [cookbook_paths]\"",
"usage_options",
".",
"each",
"do",
"|",
"option",
"|",
"expect_usage_option",
"(",
"option",
"[",
":short",
"]",
",",
"option",
"[",
":long",
"]",
",",
"option",
"[",
":description",
"]",
")",
"end",
"if",
"is_exit_zero",
"assert_no_error_occurred",
"else",
"assert_error_occurred",
"end",
"end"
] | Assert that the usage message is displayed.
@param [Boolean] is_exit_zero The exit code to check for. | [
"Assert",
"that",
"the",
"usage",
"message",
"is",
"displayed",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/command_helpers.rb#L173-L185 | train |
Foodcritic/foodcritic | features/support/command_helpers.rb | FoodCritic.InProcessHelpers.run_lint | def run_lint(cmd_args)
cd "." do
show_context = cmd_args.include?("-C")
review, @status = FoodCritic::Linter.run(CommandLine.new(cmd_args))
@review =
if review.nil? || (review.respond_to?(:warnings) && review.warnings.empty?)
""
elsif show_context
ContextOutput.new.output(review)
else
"#{review}\n"
end
end
end | ruby | def run_lint(cmd_args)
cd "." do
show_context = cmd_args.include?("-C")
review, @status = FoodCritic::Linter.run(CommandLine.new(cmd_args))
@review =
if review.nil? || (review.respond_to?(:warnings) && review.warnings.empty?)
""
elsif show_context
ContextOutput.new.output(review)
else
"#{review}\n"
end
end
end | [
"def",
"run_lint",
"(",
"cmd_args",
")",
"cd",
"\".\"",
"do",
"show_context",
"=",
"cmd_args",
".",
"include?",
"(",
"\"-C\"",
")",
"review",
",",
"@status",
"=",
"FoodCritic",
"::",
"Linter",
".",
"run",
"(",
"CommandLine",
".",
"new",
"(",
"cmd_args",
")",
")",
"@review",
"=",
"if",
"review",
".",
"nil?",
"||",
"(",
"review",
".",
"respond_to?",
"(",
":warnings",
")",
"&&",
"review",
".",
"warnings",
".",
"empty?",
")",
"\"\"",
"elsif",
"show_context",
"ContextOutput",
".",
"new",
".",
"output",
"(",
"review",
")",
"else",
"\"#{review}\\n\"",
"end",
"end",
"end"
] | Run a lint check with the provided command line arguments.
@param [Array] cmd_args The command line arguments. | [
"Run",
"a",
"lint",
"check",
"with",
"the",
"provided",
"command",
"line",
"arguments",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/command_helpers.rb#L287-L300 | train |
Foodcritic/foodcritic | features/support/command_helpers.rb | FoodCritic.BuildHelpers.assert_build_result | def assert_build_result(success, warnings)
success ? assert_no_error_occurred : assert_error_occurred
warnings.each do |code|
expect_warning(code, :warning_only => true)
end
end | ruby | def assert_build_result(success, warnings)
success ? assert_no_error_occurred : assert_error_occurred
warnings.each do |code|
expect_warning(code, :warning_only => true)
end
end | [
"def",
"assert_build_result",
"(",
"success",
",",
"warnings",
")",
"success",
"?",
"assert_no_error_occurred",
":",
"assert_error_occurred",
"warnings",
".",
"each",
"do",
"|",
"code",
"|",
"expect_warning",
"(",
"code",
",",
":warning_only",
"=>",
"true",
")",
"end",
"end"
] | Assert the build outcome
@param [Boolean] success True if the build should succeed
@param [Array] warnings The warnings expected | [
"Assert",
"the",
"build",
"outcome"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/command_helpers.rb#L312-L317 | train |
Foodcritic/foodcritic | features/support/command_helpers.rb | FoodCritic.BuildHelpers.build_tasks | def build_tasks
all_output.split("\n").map do |task|
next unless task.start_with? "rake"
task.split("#").map { |t| t.strip.sub(/^rake /, "") }
end.compact
end | ruby | def build_tasks
all_output.split("\n").map do |task|
next unless task.start_with? "rake"
task.split("#").map { |t| t.strip.sub(/^rake /, "") }
end.compact
end | [
"def",
"build_tasks",
"all_output",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"map",
"do",
"|",
"task",
"|",
"next",
"unless",
"task",
".",
"start_with?",
"\"rake\"",
"task",
".",
"split",
"(",
"\"#\"",
")",
".",
"map",
"{",
"|",
"t",
"|",
"t",
".",
"strip",
".",
"sub",
"(",
"/",
"/",
",",
"\"\"",
")",
"}",
"end",
".",
"compact",
"end"
] | The available tasks for this build
@return [Array] Task name and description | [
"The",
"available",
"tasks",
"for",
"this",
"build"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/command_helpers.rb#L334-L339 | train |
Foodcritic/foodcritic | features/support/command_helpers.rb | FoodCritic.ArubaHelpers.expect_output | def expect_output(output)
if output.respond_to?(:~)
assert_matching_output(output.to_s, all_output)
else
assert_partial_output(output, all_output)
end
end | ruby | def expect_output(output)
if output.respond_to?(:~)
assert_matching_output(output.to_s, all_output)
else
assert_partial_output(output, all_output)
end
end | [
"def",
"expect_output",
"(",
"output",
")",
"if",
"output",
".",
"respond_to?",
"(",
":~",
")",
"assert_matching_output",
"(",
"output",
".",
"to_s",
",",
"all_output",
")",
"else",
"assert_partial_output",
"(",
"output",
",",
"all_output",
")",
"end",
"end"
] | Assert that the output contains the specified warning.
@param [String] output The output to check for. | [
"Assert",
"that",
"the",
"output",
"contains",
"the",
"specified",
"warning",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/command_helpers.rb#L374-L380 | train |
Foodcritic/foodcritic | lib/foodcritic/notifications.rb | FoodCritic.Notifications.notifications | def notifications(ast)
# Sanity check the AST provided.
return [] unless ast.respond_to?(:xpath)
# We are mapping each `notifies` or `subscribes` line in the provided
# AST to a Hash with the extracted details.
notification_nodes(ast).map do |notify|
# Chef supports two styles of notification.
notified_resource = if new_style_notification?(notify)
# `notifies :restart, "service[foo]"`
new_style_notification(notify)
else
# `notifies :restart, resources(service: "foo")`
old_style_notification(notify)
end
# Ignore if the notification was not parsed
next unless notified_resource
# Now merge the extract notification details with the attributes
# that are common to both styles of notification.
notified_resource.merge(
{
# The `:type` of notification: `:subscribes` or `:notifies`.
type: notification_type(notify),
# The `:style` of notification: `:new` or `:old`.
style: new_style_notification?(notify) ? :new : :old,
# The target resource action.
action: notification_action(notify),
# The notification timing: `:before`, `:immediate` or `:delayed`.
timing: notification_timing(notify),
}
)
end.compact
end | ruby | def notifications(ast)
# Sanity check the AST provided.
return [] unless ast.respond_to?(:xpath)
# We are mapping each `notifies` or `subscribes` line in the provided
# AST to a Hash with the extracted details.
notification_nodes(ast).map do |notify|
# Chef supports two styles of notification.
notified_resource = if new_style_notification?(notify)
# `notifies :restart, "service[foo]"`
new_style_notification(notify)
else
# `notifies :restart, resources(service: "foo")`
old_style_notification(notify)
end
# Ignore if the notification was not parsed
next unless notified_resource
# Now merge the extract notification details with the attributes
# that are common to both styles of notification.
notified_resource.merge(
{
# The `:type` of notification: `:subscribes` or `:notifies`.
type: notification_type(notify),
# The `:style` of notification: `:new` or `:old`.
style: new_style_notification?(notify) ? :new : :old,
# The target resource action.
action: notification_action(notify),
# The notification timing: `:before`, `:immediate` or `:delayed`.
timing: notification_timing(notify),
}
)
end.compact
end | [
"def",
"notifications",
"(",
"ast",
")",
"# Sanity check the AST provided.",
"return",
"[",
"]",
"unless",
"ast",
".",
"respond_to?",
"(",
":xpath",
")",
"# We are mapping each `notifies` or `subscribes` line in the provided",
"# AST to a Hash with the extracted details.",
"notification_nodes",
"(",
"ast",
")",
".",
"map",
"do",
"|",
"notify",
"|",
"# Chef supports two styles of notification.",
"notified_resource",
"=",
"if",
"new_style_notification?",
"(",
"notify",
")",
"# `notifies :restart, \"service[foo]\"`",
"new_style_notification",
"(",
"notify",
")",
"else",
"# `notifies :restart, resources(service: \"foo\")`",
"old_style_notification",
"(",
"notify",
")",
"end",
"# Ignore if the notification was not parsed",
"next",
"unless",
"notified_resource",
"# Now merge the extract notification details with the attributes",
"# that are common to both styles of notification.",
"notified_resource",
".",
"merge",
"(",
"{",
"# The `:type` of notification: `:subscribes` or `:notifies`.",
"type",
":",
"notification_type",
"(",
"notify",
")",
",",
"# The `:style` of notification: `:new` or `:old`.",
"style",
":",
"new_style_notification?",
"(",
"notify",
")",
"?",
":new",
":",
":old",
",",
"# The target resource action.",
"action",
":",
"notification_action",
"(",
"notify",
")",
",",
"# The notification timing: `:before`, `:immediate` or `:delayed`.",
"timing",
":",
"notification_timing",
"(",
"notify",
")",
",",
"}",
")",
"end",
".",
"compact",
"end"
] | Extracts notification details from the provided AST, returning an
array of notification hashes.
template "/etc/www/configures-apache.conf" do
notifies :restart, "service[apache]"
end
=> [{:resource_name=>"apache",
:resource_type=>:service,
:type=>:notifies,
:style=>:new,
:action=>:restart,
:timing=>:delayed}] | [
"Extracts",
"notification",
"details",
"from",
"the",
"provided",
"AST",
"returning",
"an",
"array",
"of",
"notification",
"hashes",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/notifications.rb#L20-L58 | train |
Foodcritic/foodcritic | lib/foodcritic/notifications.rb | FoodCritic.Notifications.notification_action | def notification_action(notify)
is_variable = true unless notify.xpath("args_add_block/args_add//args_add[aref or vcall or call or var_ref]").empty?
string_val = notify.xpath("descendant::args_add/string_literal/string_add/tstring_content/@value").first
symbol_val = notify.xpath('descendant::args_add/args_add//symbol/ident/@value |
descendant::dyna_symbol[1]/xstring_add/tstring_content/@value').first
# 1) return a nil if the action is a variable like node['foo']['bar']
# 2) return the symbol if it exists
# 3) return the string since we're positive that we're not a symbol or variable
return nil if is_variable
return symbol_val.value.to_sym unless symbol_val.nil?
string_val.value
end | ruby | def notification_action(notify)
is_variable = true unless notify.xpath("args_add_block/args_add//args_add[aref or vcall or call or var_ref]").empty?
string_val = notify.xpath("descendant::args_add/string_literal/string_add/tstring_content/@value").first
symbol_val = notify.xpath('descendant::args_add/args_add//symbol/ident/@value |
descendant::dyna_symbol[1]/xstring_add/tstring_content/@value').first
# 1) return a nil if the action is a variable like node['foo']['bar']
# 2) return the symbol if it exists
# 3) return the string since we're positive that we're not a symbol or variable
return nil if is_variable
return symbol_val.value.to_sym unless symbol_val.nil?
string_val.value
end | [
"def",
"notification_action",
"(",
"notify",
")",
"is_variable",
"=",
"true",
"unless",
"notify",
".",
"xpath",
"(",
"\"args_add_block/args_add//args_add[aref or vcall or call or var_ref]\"",
")",
".",
"empty?",
"string_val",
"=",
"notify",
".",
"xpath",
"(",
"\"descendant::args_add/string_literal/string_add/tstring_content/@value\"",
")",
".",
"first",
"symbol_val",
"=",
"notify",
".",
"xpath",
"(",
"'descendant::args_add/args_add//symbol/ident/@value |\n descendant::dyna_symbol[1]/xstring_add/tstring_content/@value'",
")",
".",
"first",
"# 1) return a nil if the action is a variable like node['foo']['bar']",
"# 2) return the symbol if it exists",
"# 3) return the string since we're positive that we're not a symbol or variable",
"return",
"nil",
"if",
"is_variable",
"return",
"symbol_val",
".",
"value",
".",
"to_sym",
"unless",
"symbol_val",
".",
"nil?",
"string_val",
".",
"value",
"end"
] | return the notification action as either a symbol or string or nil if it's a variable.
Yes you can notify an action as a string but it's wrong and we want to return it as
a string so we can tell people not to do that. | [
"return",
"the",
"notification",
"action",
"as",
"either",
"a",
"symbol",
"or",
"string",
"or",
"nil",
"if",
"it",
"s",
"a",
"variable",
".",
"Yes",
"you",
"can",
"notify",
"an",
"action",
"as",
"a",
"string",
"but",
"it",
"s",
"wrong",
"and",
"we",
"want",
"to",
"return",
"it",
"as",
"a",
"string",
"so",
"we",
"can",
"tell",
"people",
"not",
"to",
"do",
"that",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/notifications.rb#L132-L144 | train |
Foodcritic/foodcritic | features/support/cookbook_helpers.rb | FoodCritic.CookbookHelpers.cookbook_that_matches_rules | def cookbook_that_matches_rules(codes)
recipe = ""
codes.each do |code|
if code == "FC002"
recipe += %q{
directory "#{node['base_dir']}" do
action :create
end
}
elsif code == "FC004"
recipe += %q{
execute "stop-jetty" do
command "/etc/init.d/jetty6 stop"
action :run
end
}
elsif code == "FC005"
recipe += %q{
package 'erlang-base' do
action :upgrade
end
package 'erlang-corba' do
action :upgrade
end
package 'erlang-another' do
action :upgrade
end
}
elsif code == "FC006"
recipe += %q{
directory "/var/lib/foo" do
mode 644
action :create
end
}
end
end
write_recipe(recipe)
write_file("cookbooks/example/recipes/server.rb", "")
write_readme("Hello World") # Don't trigger FC011
write_metadata(%q{
name 'example'
maintainer 'A Maintainer'
maintainer_email '[email protected]'
version '0.0.1'
issues_url 'http://github.com/foo/bar_cookbook/issues'
source_url 'http://github.com/foo/bar_cookbook'
}.strip)
end | ruby | def cookbook_that_matches_rules(codes)
recipe = ""
codes.each do |code|
if code == "FC002"
recipe += %q{
directory "#{node['base_dir']}" do
action :create
end
}
elsif code == "FC004"
recipe += %q{
execute "stop-jetty" do
command "/etc/init.d/jetty6 stop"
action :run
end
}
elsif code == "FC005"
recipe += %q{
package 'erlang-base' do
action :upgrade
end
package 'erlang-corba' do
action :upgrade
end
package 'erlang-another' do
action :upgrade
end
}
elsif code == "FC006"
recipe += %q{
directory "/var/lib/foo" do
mode 644
action :create
end
}
end
end
write_recipe(recipe)
write_file("cookbooks/example/recipes/server.rb", "")
write_readme("Hello World") # Don't trigger FC011
write_metadata(%q{
name 'example'
maintainer 'A Maintainer'
maintainer_email '[email protected]'
version '0.0.1'
issues_url 'http://github.com/foo/bar_cookbook/issues'
source_url 'http://github.com/foo/bar_cookbook'
}.strip)
end | [
"def",
"cookbook_that_matches_rules",
"(",
"codes",
")",
"recipe",
"=",
"\"\"",
"codes",
".",
"each",
"do",
"|",
"code",
"|",
"if",
"code",
"==",
"\"FC002\"",
"recipe",
"+=",
"%q{\n directory \"#{node['base_dir']}\" do\n action :create\n end\n }",
"elsif",
"code",
"==",
"\"FC004\"",
"recipe",
"+=",
"%q{\n execute \"stop-jetty\" do\n command \"/etc/init.d/jetty6 stop\"\n action :run\n end\n }",
"elsif",
"code",
"==",
"\"FC005\"",
"recipe",
"+=",
"%q{\n package 'erlang-base' do\n action :upgrade\n end\n package 'erlang-corba' do\n action :upgrade\n end\n package 'erlang-another' do\n action :upgrade\n end\n }",
"elsif",
"code",
"==",
"\"FC006\"",
"recipe",
"+=",
"%q{\n directory \"/var/lib/foo\" do\n mode 644\n action :create\n end\n }",
"end",
"end",
"write_recipe",
"(",
"recipe",
")",
"write_file",
"(",
"\"cookbooks/example/recipes/server.rb\"",
",",
"\"\"",
")",
"write_readme",
"(",
"\"Hello World\"",
")",
"# Don't trigger FC011",
"write_metadata",
"(",
"%q{\n name 'example'\n maintainer 'A Maintainer'\n maintainer_email '[email protected]'\n version '0.0.1'\n issues_url 'http://github.com/foo/bar_cookbook/issues'\n source_url 'http://github.com/foo/bar_cookbook'\n }",
".",
"strip",
")",
"end"
] | Create a cookbook that will match the specified rules.
@param [Array] codes The codes to match. Only FC002, FC004 and FC005 and FC006 are supported. | [
"Create",
"a",
"cookbook",
"that",
"will",
"match",
"the",
"specified",
"rules",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/cookbook_helpers.rb#L47-L95 | train |
Foodcritic/foodcritic | features/support/cookbook_helpers.rb | FoodCritic.CookbookHelpers.cookbook_with_lwrp | def cookbook_with_lwrp(lwrp)
lwrp = { :default_action => false, :notifies => :does_not_notify,
:use_inline_resources => false }.merge!(lwrp)
ruby_default_action = %q{
def initialize(*args)
super
@action = :create
end
}.strip
write_resource("site", %Q{
actions :create
attribute :name, :kind_of => String, :name_attribute => true
#{ruby_default_action if lwrp[:default_action] == :ruby_default_action}
#{'default_action :create' if lwrp[:default_action] == :dsl_default_action}
})
notifications = { :does_notify => "new_resource.updated_by_last_action(true)",
:does_notify_without_parens => "new_resource.updated_by_last_action true",
:deprecated_syntax => "new_resource.updated = true",
:class_variable => "@updated = true" }
write_provider("site", %Q{
#{'use_inline_resources' if lwrp[:use_inline_resources]}
action :create do
log "Here is where I would create a site"
#{notifications[lwrp[:notifies]]}
end
})
end | ruby | def cookbook_with_lwrp(lwrp)
lwrp = { :default_action => false, :notifies => :does_not_notify,
:use_inline_resources => false }.merge!(lwrp)
ruby_default_action = %q{
def initialize(*args)
super
@action = :create
end
}.strip
write_resource("site", %Q{
actions :create
attribute :name, :kind_of => String, :name_attribute => true
#{ruby_default_action if lwrp[:default_action] == :ruby_default_action}
#{'default_action :create' if lwrp[:default_action] == :dsl_default_action}
})
notifications = { :does_notify => "new_resource.updated_by_last_action(true)",
:does_notify_without_parens => "new_resource.updated_by_last_action true",
:deprecated_syntax => "new_resource.updated = true",
:class_variable => "@updated = true" }
write_provider("site", %Q{
#{'use_inline_resources' if lwrp[:use_inline_resources]}
action :create do
log "Here is where I would create a site"
#{notifications[lwrp[:notifies]]}
end
})
end | [
"def",
"cookbook_with_lwrp",
"(",
"lwrp",
")",
"lwrp",
"=",
"{",
":default_action",
"=>",
"false",
",",
":notifies",
"=>",
":does_not_notify",
",",
":use_inline_resources",
"=>",
"false",
"}",
".",
"merge!",
"(",
"lwrp",
")",
"ruby_default_action",
"=",
"%q{\n def initialize(*args)\n super\n @action = :create\n end\n }",
".",
"strip",
"write_resource",
"(",
"\"site\"",
",",
"%Q{\n actions :create\n attribute :name, :kind_of => String, :name_attribute => true\n #{ruby_default_action if lwrp[:default_action] == :ruby_default_action}\n #{'default_action :create' if lwrp[:default_action] == :dsl_default_action}\n }",
")",
"notifications",
"=",
"{",
":does_notify",
"=>",
"\"new_resource.updated_by_last_action(true)\"",
",",
":does_notify_without_parens",
"=>",
"\"new_resource.updated_by_last_action true\"",
",",
":deprecated_syntax",
"=>",
"\"new_resource.updated = true\"",
",",
":class_variable",
"=>",
"\"@updated = true\"",
"}",
"write_provider",
"(",
"\"site\"",
",",
"%Q{\n #{'use_inline_resources' if lwrp[:use_inline_resources]}\n action :create do\n log \"Here is where I would create a site\"\n #{notifications[lwrp[:notifies]]}\n end\n }",
")",
"end"
] | Create a cookbook with a LRWP
@param [Hash] lwrp The options to use for the created LWRP
@option lwrp [Symbol] :default_action One of :no_default_action, :ruby_default_action, :dsl_default_action
@option lwrp [Symbol] :notifies One of :does_not_notify, :does_notify, :does_notify_without_parens, :deprecated_syntax, :class_variable
@option lwrp [Symbol] :use_inline_resources Defaults to false | [
"Create",
"a",
"cookbook",
"with",
"a",
"LRWP"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/cookbook_helpers.rb#L124-L150 | train |
Foodcritic/foodcritic | features/support/cookbook_helpers.rb | FoodCritic.CookbookHelpers.cookbook_with_maintainer | def cookbook_with_maintainer(name, email)
write_recipe %q{
#
# Cookbook Name:: example
# Recipe:: default
#
# Copyright 2011, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
}
fields = {}
fields["maintainer"] = name unless name.nil?
fields["maintainer_email"] = email unless email.nil?
write_metadata %Q{
#{fields.map { |field, value| %Q{#{field}\t"#{value}"} }.join("\n")}
license "All rights reserved"
description "Installs/Configures example"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version "0.0.1"
}
end | ruby | def cookbook_with_maintainer(name, email)
write_recipe %q{
#
# Cookbook Name:: example
# Recipe:: default
#
# Copyright 2011, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
}
fields = {}
fields["maintainer"] = name unless name.nil?
fields["maintainer_email"] = email unless email.nil?
write_metadata %Q{
#{fields.map { |field, value| %Q{#{field}\t"#{value}"} }.join("\n")}
license "All rights reserved"
description "Installs/Configures example"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version "0.0.1"
}
end | [
"def",
"cookbook_with_maintainer",
"(",
"name",
",",
"email",
")",
"write_recipe",
"%q{\n #\n # Cookbook Name:: example\n # Recipe:: default\n #\n # Copyright 2011, YOUR_COMPANY_NAME\n #\n # All rights reserved - Do Not Redistribute\n #\n }",
"fields",
"=",
"{",
"}",
"fields",
"[",
"\"maintainer\"",
"]",
"=",
"name",
"unless",
"name",
".",
"nil?",
"fields",
"[",
"\"maintainer_email\"",
"]",
"=",
"email",
"unless",
"email",
".",
"nil?",
"write_metadata",
"%Q{\n #{fields.map { |field, value| %Q{#{field}\\t\"#{value}\"} }.join(\"\\n\")}\n license \"All rights reserved\"\n description \"Installs/Configures example\"\n long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))\n version \"0.0.1\"\n }",
"end"
] | Create an cookbook with the maintainer specified in the metadata
@param [String] name The maintainer name
@param [String] email The maintainer email address | [
"Create",
"an",
"cookbook",
"with",
"the",
"maintainer",
"specified",
"in",
"the",
"metadata"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/cookbook_helpers.rb#L164-L186 | train |
Foodcritic/foodcritic | features/support/cookbook_helpers.rb | FoodCritic.CookbookHelpers.rakefile | def rakefile(task, options)
rakefile_content = "task :default => []"
task_def = case task
when :no_block then "FoodCritic::Rake::LintTask.new"
else %Q{
FoodCritic::Rake::LintTask.new do |t|
#{"t.name = '#{options[:name]}'" if options[:name]}
#{"t.files = #{options[:files]}" if options[:files]}
#{"t.options = #{options[:options]}" if options[:options]}
end
}
end
if task_def
rakefile_content = %Q{
require 'foodcritic'
task :default => [:#{options[:name] ? options[:name] : 'foodcritic'}]
#{task_def}
}
end
write_file "cookbooks/example/Rakefile", rakefile_content
end | ruby | def rakefile(task, options)
rakefile_content = "task :default => []"
task_def = case task
when :no_block then "FoodCritic::Rake::LintTask.new"
else %Q{
FoodCritic::Rake::LintTask.new do |t|
#{"t.name = '#{options[:name]}'" if options[:name]}
#{"t.files = #{options[:files]}" if options[:files]}
#{"t.options = #{options[:options]}" if options[:options]}
end
}
end
if task_def
rakefile_content = %Q{
require 'foodcritic'
task :default => [:#{options[:name] ? options[:name] : 'foodcritic'}]
#{task_def}
}
end
write_file "cookbooks/example/Rakefile", rakefile_content
end | [
"def",
"rakefile",
"(",
"task",
",",
"options",
")",
"rakefile_content",
"=",
"\"task :default => []\"",
"task_def",
"=",
"case",
"task",
"when",
":no_block",
"then",
"\"FoodCritic::Rake::LintTask.new\"",
"else",
"%Q{\n FoodCritic::Rake::LintTask.new do |t|\n #{\"t.name = '#{options[:name]}'\" if options[:name]}\n #{\"t.files = #{options[:files]}\" if options[:files]}\n #{\"t.options = #{options[:options]}\" if options[:options]}\n end\n }",
"end",
"if",
"task_def",
"rakefile_content",
"=",
"%Q{\n require 'foodcritic'\n task :default => [:#{options[:name] ? options[:name] : 'foodcritic'}]\n #{task_def}\n }",
"end",
"write_file",
"\"cookbooks/example/Rakefile\"",
",",
"rakefile_content",
"end"
] | Create a Rakefile that uses the linter rake task
@param [Symbol] task Type of task
@param [Hash] options Task options
@option options [String] :name Task name
@option options [String] :files Files to process
@option options [String] :options The options to set on the rake task | [
"Create",
"a",
"Rakefile",
"that",
"uses",
"the",
"linter",
"rake",
"task"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/cookbook_helpers.rb#L242-L262 | train |
Foodcritic/foodcritic | features/support/cookbook_helpers.rb | FoodCritic.CookbookHelpers.recipe_installs_gem | def recipe_installs_gem(type, action = :install)
case type
when :simple
write_recipe %Q{
gem_package "bluepill" do
action :#{action}
end
}.strip
when :compile_time
write_recipe %Q{
r = gem_package "mysql" do
action :nothing
end
r.run_action(:#{action})
Gem.clear_paths
}.strip
when :compile_time_from_array
write_recipe %Q{
['foo', 'bar', 'baz'].each do |pkg|
r = gem_package pkg do
action :nothing
end
r.run_action(:#{action})
end
}.strip
when :compile_time_from_word_list
write_recipe %Q{
%w{foo bar baz}.each do |pkg|
r = gem_package pkg do
action :nothing
end
r.run_action(:#{action})
end
}.strip
else
raise "Unrecognised type: #{type}"
end
end | ruby | def recipe_installs_gem(type, action = :install)
case type
when :simple
write_recipe %Q{
gem_package "bluepill" do
action :#{action}
end
}.strip
when :compile_time
write_recipe %Q{
r = gem_package "mysql" do
action :nothing
end
r.run_action(:#{action})
Gem.clear_paths
}.strip
when :compile_time_from_array
write_recipe %Q{
['foo', 'bar', 'baz'].each do |pkg|
r = gem_package pkg do
action :nothing
end
r.run_action(:#{action})
end
}.strip
when :compile_time_from_word_list
write_recipe %Q{
%w{foo bar baz}.each do |pkg|
r = gem_package pkg do
action :nothing
end
r.run_action(:#{action})
end
}.strip
else
raise "Unrecognised type: #{type}"
end
end | [
"def",
"recipe_installs_gem",
"(",
"type",
",",
"action",
"=",
":install",
")",
"case",
"type",
"when",
":simple",
"write_recipe",
"%Q{\n gem_package \"bluepill\" do\n action :#{action}\n end\n }",
".",
"strip",
"when",
":compile_time",
"write_recipe",
"%Q{\n r = gem_package \"mysql\" do\n action :nothing\n end\n\n r.run_action(:#{action})\n Gem.clear_paths\n }",
".",
"strip",
"when",
":compile_time_from_array",
"write_recipe",
"%Q{\n ['foo', 'bar', 'baz'].each do |pkg|\n r = gem_package pkg do\n action :nothing\n end\n r.run_action(:#{action})\n end\n }",
".",
"strip",
"when",
":compile_time_from_word_list",
"write_recipe",
"%Q{\n %w{foo bar baz}.each do |pkg|\n r = gem_package pkg do\n action :nothing\n end\n r.run_action(:#{action})\n end\n }",
".",
"strip",
"else",
"raise",
"\"Unrecognised type: #{type}\"",
"end",
"end"
] | Install a gem using the specified approach.
@param [Symbol] type The type of approach, one of :simple, :compile_time,
:compile_time_from_array, :compile_time_from_word_list
@param [Symbol] action Either :install or :upgrade | [
"Install",
"a",
"gem",
"using",
"the",
"specified",
"approach",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/cookbook_helpers.rb#L284-L322 | train |
Foodcritic/foodcritic | features/support/cookbook_helpers.rb | FoodCritic.CookbookHelpers.recipe_with_dependency | def recipe_with_dependency(dep)
dep = { :is_scoped => true, :is_declared => true,
:parentheses => false }.merge!(dep)
recipe = "foo#{dep[:is_scoped] ? '::default' : ''}"
write_recipe(if dep[:parentheses]
"include_recipe('#{recipe}')"
else
"include_recipe '#{recipe}'"
end)
write_metadata %Q{
version "1.9.0"
depends "#{dep[:is_declared] ? 'foo' : 'dogs'}"
}
end | ruby | def recipe_with_dependency(dep)
dep = { :is_scoped => true, :is_declared => true,
:parentheses => false }.merge!(dep)
recipe = "foo#{dep[:is_scoped] ? '::default' : ''}"
write_recipe(if dep[:parentheses]
"include_recipe('#{recipe}')"
else
"include_recipe '#{recipe}'"
end)
write_metadata %Q{
version "1.9.0"
depends "#{dep[:is_declared] ? 'foo' : 'dogs'}"
}
end | [
"def",
"recipe_with_dependency",
"(",
"dep",
")",
"dep",
"=",
"{",
":is_scoped",
"=>",
"true",
",",
":is_declared",
"=>",
"true",
",",
":parentheses",
"=>",
"false",
"}",
".",
"merge!",
"(",
"dep",
")",
"recipe",
"=",
"\"foo#{dep[:is_scoped] ? '::default' : ''}\"",
"write_recipe",
"(",
"if",
"dep",
"[",
":parentheses",
"]",
"\"include_recipe('#{recipe}')\"",
"else",
"\"include_recipe '#{recipe}'\"",
"end",
")",
"write_metadata",
"%Q{\n version \"1.9.0\"\n depends \"#{dep[:is_declared] ? 'foo' : 'dogs'}\"\n }",
"end"
] | Create a recipe with an external dependency on another cookbook.
@param [Hash] dep The options to use for dependency
@option dep [Boolean] :is_declared True if this dependency has been declared in the cookbook metadata
@option dep [Boolean] :is_scoped True if the include_recipe references a specific recipe or the cookbook
@option dep [Boolean] :parentheses True if the include_recipe is called with parentheses | [
"Create",
"a",
"recipe",
"with",
"an",
"external",
"dependency",
"on",
"another",
"cookbook",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/cookbook_helpers.rb#L348-L361 | train |
Foodcritic/foodcritic | features/support/cookbook_helpers.rb | FoodCritic.CookbookHelpers.recipe_with_ruby_block | def recipe_with_ruby_block(length)
recipe = ""
if length == :short || length == :both
recipe << %q{
ruby_block "subexpressions" do
block do
rc = Chef::Util::FileEdit.new("/foo/bar.conf")
rc.search_file_replace_line(/^search/, "search #{node["foo"]["bar"]} compute-1.internal")
rc.search_file_replace_line(/^domain/, "domain #{node["foo"]["bar"]}")
rc.write_file
end
action :create
end
}
end
if length == :long || length == :both
recipe << %q{
ruby_block "too_long" do
block do
begin
do_something('with argument')
do_something_else('with another argument')
foo = Foo.new('bar')
foo.activate_turbo_boost
foo.each do |thing|
case thing
when "fee"
puts 'Fee'
when "fi"
puts 'Fi'
when "fo"
puts 'Fo'
else
puts "Fum"
end
end
rescue Some::Exception
Chef::Log.warn "Problem activating the turbo boost"
end
end
action :create
end
}
end
write_recipe(recipe)
end | ruby | def recipe_with_ruby_block(length)
recipe = ""
if length == :short || length == :both
recipe << %q{
ruby_block "subexpressions" do
block do
rc = Chef::Util::FileEdit.new("/foo/bar.conf")
rc.search_file_replace_line(/^search/, "search #{node["foo"]["bar"]} compute-1.internal")
rc.search_file_replace_line(/^domain/, "domain #{node["foo"]["bar"]}")
rc.write_file
end
action :create
end
}
end
if length == :long || length == :both
recipe << %q{
ruby_block "too_long" do
block do
begin
do_something('with argument')
do_something_else('with another argument')
foo = Foo.new('bar')
foo.activate_turbo_boost
foo.each do |thing|
case thing
when "fee"
puts 'Fee'
when "fi"
puts 'Fi'
when "fo"
puts 'Fo'
else
puts "Fum"
end
end
rescue Some::Exception
Chef::Log.warn "Problem activating the turbo boost"
end
end
action :create
end
}
end
write_recipe(recipe)
end | [
"def",
"recipe_with_ruby_block",
"(",
"length",
")",
"recipe",
"=",
"\"\"",
"if",
"length",
"==",
":short",
"||",
"length",
"==",
":both",
"recipe",
"<<",
"%q{\n ruby_block \"subexpressions\" do\n\t block do\n\t rc = Chef::Util::FileEdit.new(\"/foo/bar.conf\")\n rc.search_file_replace_line(/^search/, \"search #{node[\"foo\"][\"bar\"]} compute-1.internal\")\n rc.search_file_replace_line(/^domain/, \"domain #{node[\"foo\"][\"bar\"]}\")\n rc.write_file\n end\n action :create\n end\n }",
"end",
"if",
"length",
"==",
":long",
"||",
"length",
"==",
":both",
"recipe",
"<<",
"%q{\n ruby_block \"too_long\" do\n block do\n begin\n do_something('with argument')\n do_something_else('with another argument')\n foo = Foo.new('bar')\n foo.activate_turbo_boost\n foo.each do |thing|\n case thing\n when \"fee\"\n puts 'Fee'\n when \"fi\"\n puts 'Fi'\n when \"fo\"\n puts 'Fo'\n else\n puts \"Fum\"\n end\n end\n rescue Some::Exception\n Chef::Log.warn \"Problem activating the turbo boost\"\n end\n end\n action :create\n end\n }",
"end",
"write_recipe",
"(",
"recipe",
")",
"end"
] | Create a recipe with a ruby_block resource.
@param [Symbol] length A :short or :long block, or :both | [
"Create",
"a",
"recipe",
"with",
"a",
"ruby_block",
"resource",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/cookbook_helpers.rb#L396-L441 | train |
Foodcritic/foodcritic | features/support/cookbook_helpers.rb | FoodCritic.CookbookHelpers.role | def role(options = {})
options = { :format => :ruby, :dir => "roles" }.merge(options)
content = if options[:format] == :json
%Q{
{
"chef_type": "role",
"json_class": "Chef::Role",
#{Array(options[:role_name]).map { |r| "name: #{r}," }.join("\n")}
"run_list": [
"recipe[apache2]",
]
}
}
else
%Q{
#{Array(options[:role_name]).map { |r| "name #{r}" }.join("\n")}
run_list "recipe[apache2]"
}
end
write_file "#{options[:dir]}/#{options[:file_name]}", content.strip
end | ruby | def role(options = {})
options = { :format => :ruby, :dir => "roles" }.merge(options)
content = if options[:format] == :json
%Q{
{
"chef_type": "role",
"json_class": "Chef::Role",
#{Array(options[:role_name]).map { |r| "name: #{r}," }.join("\n")}
"run_list": [
"recipe[apache2]",
]
}
}
else
%Q{
#{Array(options[:role_name]).map { |r| "name #{r}" }.join("\n")}
run_list "recipe[apache2]"
}
end
write_file "#{options[:dir]}/#{options[:file_name]}", content.strip
end | [
"def",
"role",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":format",
"=>",
":ruby",
",",
":dir",
"=>",
"\"roles\"",
"}",
".",
"merge",
"(",
"options",
")",
"content",
"=",
"if",
"options",
"[",
":format",
"]",
"==",
":json",
"%Q{\n {\n \"chef_type\": \"role\",\n \"json_class\": \"Chef::Role\",\n #{Array(options[:role_name]).map { |r| \"name: #{r},\" }.join(\"\\n\")}\n \"run_list\": [\n \"recipe[apache2]\",\n ]\n }\n }",
"else",
"%Q{\n #{Array(options[:role_name]).map { |r| \"name #{r}\" }.join(\"\\n\")}\n run_list \"recipe[apache2]\"\n }",
"end",
"write_file",
"\"#{options[:dir]}/#{options[:file_name]}\"",
",",
"content",
".",
"strip",
"end"
] | Create a role file
@param [Hash] options The options to use for the role
@option options [String] :role_name The name of the role declared in the role file
@option options [String] :file_name The containing file relative to the roles directory
@option options [Symbol] :format Either :ruby or :json. Default is :ruby | [
"Create",
"a",
"role",
"file"
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/features/support/cookbook_helpers.rb#L462-L482 | train |
Foodcritic/foodcritic | lib/foodcritic/domain.rb | FoodCritic.Review.to_s | def to_s
# Sorted by filename and line number.
#
# FC123: My rule name: foo/recipes/default.rb
@warnings.map do |w|
["#{w.rule.code}: #{w.rule.name}: #{w.match[:filename]}",
w.match[:line].to_i]
end.sort do |x, y|
x.first == y.first ? x[1] <=> y[1] : x.first <=> y.first
end.map { |w| "#{w.first}:#{w[1]}" }.uniq.join("\n")
end | ruby | def to_s
# Sorted by filename and line number.
#
# FC123: My rule name: foo/recipes/default.rb
@warnings.map do |w|
["#{w.rule.code}: #{w.rule.name}: #{w.match[:filename]}",
w.match[:line].to_i]
end.sort do |x, y|
x.first == y.first ? x[1] <=> y[1] : x.first <=> y.first
end.map { |w| "#{w.first}:#{w[1]}" }.uniq.join("\n")
end | [
"def",
"to_s",
"# Sorted by filename and line number.",
"#",
"# FC123: My rule name: foo/recipes/default.rb",
"@warnings",
".",
"map",
"do",
"|",
"w",
"|",
"[",
"\"#{w.rule.code}: #{w.rule.name}: #{w.match[:filename]}\"",
",",
"w",
".",
"match",
"[",
":line",
"]",
".",
"to_i",
"]",
"end",
".",
"sort",
"do",
"|",
"x",
",",
"y",
"|",
"x",
".",
"first",
"==",
"y",
".",
"first",
"?",
"x",
"[",
"1",
"]",
"<=>",
"y",
"[",
"1",
"]",
":",
"x",
".",
"first",
"<=>",
"y",
".",
"first",
"end",
".",
"map",
"{",
"|",
"w",
"|",
"\"#{w.first}:#{w[1]}\"",
"}",
".",
"uniq",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Returns a string representation of this review. This representation is
liable to change. | [
"Returns",
"a",
"string",
"representation",
"of",
"this",
"review",
".",
"This",
"representation",
"is",
"liable",
"to",
"change",
"."
] | f06e354833c75caa91a800e0f9343ece5185a737 | https://github.com/Foodcritic/foodcritic/blob/f06e354833c75caa91a800e0f9343ece5185a737/lib/foodcritic/domain.rb#L63-L73 | train |
arangamani/jenkins_api_client | lib/jenkins_api_client/client.rb | JenkinsApi.Client.get_artifact | def get_artifact(job_name,filename)
@artifact = job.find_artifact(job_name)
response = make_http_request(Net::HTTP::Get.new(@artifact))
if response.code == "200"
File.write(File.expand_path(filename), response.body)
else
raise "Couldn't get the artifact"
end
end | ruby | def get_artifact(job_name,filename)
@artifact = job.find_artifact(job_name)
response = make_http_request(Net::HTTP::Get.new(@artifact))
if response.code == "200"
File.write(File.expand_path(filename), response.body)
else
raise "Couldn't get the artifact"
end
end | [
"def",
"get_artifact",
"(",
"job_name",
",",
"filename",
")",
"@artifact",
"=",
"job",
".",
"find_artifact",
"(",
"job_name",
")",
"response",
"=",
"make_http_request",
"(",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"@artifact",
")",
")",
"if",
"response",
".",
"code",
"==",
"\"200\"",
"File",
".",
"write",
"(",
"File",
".",
"expand_path",
"(",
"filename",
")",
",",
"response",
".",
"body",
")",
"else",
"raise",
"\"Couldn't get the artifact\"",
"end",
"end"
] | Connects to the server and downloads artifacts to a specified location
@param [String] job_name
@param [String] filename location to save artifact | [
"Connects",
"to",
"the",
"server",
"and",
"downloads",
"artifacts",
"to",
"a",
"specified",
"location"
] | 72f49f2e7ef12d58a0e33856ca91962b2e27709b | https://github.com/arangamani/jenkins_api_client/blob/72f49f2e7ef12d58a0e33856ca91962b2e27709b/lib/jenkins_api_client/client.rb#L286-L294 | train |
arangamani/jenkins_api_client | lib/jenkins_api_client/client.rb | JenkinsApi.Client.get_artifacts | def get_artifacts(job_name, dldir, build_number = nil)
@artifacts = job.find_artifacts(job_name,build_number)
results = []
@artifacts.each do |artifact|
uri = URI.parse(artifact)
http = Net::HTTP.new(uri.host, uri.port)
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.use_ssl = @ssl
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth(@username, @password)
response = http.request(request)
# we want every thing after the last 'build' in the path to become the filename
if artifact.include?('/build/')
filename = artifact.split("/build/").last.gsub('/','-')
else
filename = File.basename(artifact)
end
filename = File.join(dldir, filename)
results << filename
if response.code == "200"
File.write(File.expand_path(filename), response.body)
else
raise "Couldn't get the artifact #{artifact} for job #{job}"
end
end
results
end | ruby | def get_artifacts(job_name, dldir, build_number = nil)
@artifacts = job.find_artifacts(job_name,build_number)
results = []
@artifacts.each do |artifact|
uri = URI.parse(artifact)
http = Net::HTTP.new(uri.host, uri.port)
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.use_ssl = @ssl
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth(@username, @password)
response = http.request(request)
# we want every thing after the last 'build' in the path to become the filename
if artifact.include?('/build/')
filename = artifact.split("/build/").last.gsub('/','-')
else
filename = File.basename(artifact)
end
filename = File.join(dldir, filename)
results << filename
if response.code == "200"
File.write(File.expand_path(filename), response.body)
else
raise "Couldn't get the artifact #{artifact} for job #{job}"
end
end
results
end | [
"def",
"get_artifacts",
"(",
"job_name",
",",
"dldir",
",",
"build_number",
"=",
"nil",
")",
"@artifacts",
"=",
"job",
".",
"find_artifacts",
"(",
"job_name",
",",
"build_number",
")",
"results",
"=",
"[",
"]",
"@artifacts",
".",
"each",
"do",
"|",
"artifact",
"|",
"uri",
"=",
"URI",
".",
"parse",
"(",
"artifact",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"http",
".",
"use_ssl",
"=",
"@ssl",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"request_uri",
")",
"request",
".",
"basic_auth",
"(",
"@username",
",",
"@password",
")",
"response",
"=",
"http",
".",
"request",
"(",
"request",
")",
"# we want every thing after the last 'build' in the path to become the filename",
"if",
"artifact",
".",
"include?",
"(",
"'/build/'",
")",
"filename",
"=",
"artifact",
".",
"split",
"(",
"\"/build/\"",
")",
".",
"last",
".",
"gsub",
"(",
"'/'",
",",
"'-'",
")",
"else",
"filename",
"=",
"File",
".",
"basename",
"(",
"artifact",
")",
"end",
"filename",
"=",
"File",
".",
"join",
"(",
"dldir",
",",
"filename",
")",
"results",
"<<",
"filename",
"if",
"response",
".",
"code",
"==",
"\"200\"",
"File",
".",
"write",
"(",
"File",
".",
"expand_path",
"(",
"filename",
")",
",",
"response",
".",
"body",
")",
"else",
"raise",
"\"Couldn't get the artifact #{artifact} for job #{job}\"",
"end",
"end",
"results",
"end"
] | Connects to the server and download all artifacts of a build to a specified location
@param [String] job_name
@param [String] dldir location to save artifacts
@param [Integer] build_number optional, defaults to current build
@returns [String, Array] list of retrieved artifacts | [
"Connects",
"to",
"the",
"server",
"and",
"download",
"all",
"artifacts",
"of",
"a",
"build",
"to",
"a",
"specified",
"location"
] | 72f49f2e7ef12d58a0e33856ca91962b2e27709b | https://github.com/arangamani/jenkins_api_client/blob/72f49f2e7ef12d58a0e33856ca91962b2e27709b/lib/jenkins_api_client/client.rb#L303-L329 | train |
arangamani/jenkins_api_client | lib/jenkins_api_client/client.rb | JenkinsApi.Client.make_http_request | def make_http_request(request, follow_redirect = @follow_redirects)
request.basic_auth @username, @password if @username
request['Cookie'] = @cookies if @cookies
if @proxy_ip
case @proxy_protocol
when 'http'
http = Net::HTTP::Proxy(@proxy_ip, @proxy_port).new(@server_ip, @server_port)
when 'socks'
http = Net::HTTP::SOCKSProxy(@proxy_ip, @proxy_port).start(@server_ip, @server_port)
else
raise "unknown proxy protocol: '#{@proxy_protocol}'"
end
else
http = Net::HTTP.new(@server_ip, @server_port)
end
if @ssl && @pkcs_file_path
http.use_ssl = true
pkcs12 =OpenSSL::PKCS12.new(File.binread(@pkcs_file_path), @pass_phrase!=nil ? @pass_phrase : "")
http.cert = pkcs12.certificate
http.key = pkcs12.key
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
elsif @ssl
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.ca_file = @ca_file if @ca_file
end
http.open_timeout = @http_open_timeout
http.read_timeout = @http_read_timeout
response = http.request(request)
case response
when Net::HTTPRedirection then
# If we got a redirect request, follow it (if flag set), but don't
# go any deeper (only one redirect supported - don't want to follow
# our tail)
if follow_redirect
redir_uri = URI.parse(response['location'])
response = make_http_request(
Net::HTTP::Get.new(redir_uri.path, false)
)
end
end
# Pick out some useful header info before we return
@jenkins_version = response['X-Jenkins']
@hudson_version = response['X-Hudson']
return response
end | ruby | def make_http_request(request, follow_redirect = @follow_redirects)
request.basic_auth @username, @password if @username
request['Cookie'] = @cookies if @cookies
if @proxy_ip
case @proxy_protocol
when 'http'
http = Net::HTTP::Proxy(@proxy_ip, @proxy_port).new(@server_ip, @server_port)
when 'socks'
http = Net::HTTP::SOCKSProxy(@proxy_ip, @proxy_port).start(@server_ip, @server_port)
else
raise "unknown proxy protocol: '#{@proxy_protocol}'"
end
else
http = Net::HTTP.new(@server_ip, @server_port)
end
if @ssl && @pkcs_file_path
http.use_ssl = true
pkcs12 =OpenSSL::PKCS12.new(File.binread(@pkcs_file_path), @pass_phrase!=nil ? @pass_phrase : "")
http.cert = pkcs12.certificate
http.key = pkcs12.key
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
elsif @ssl
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.ca_file = @ca_file if @ca_file
end
http.open_timeout = @http_open_timeout
http.read_timeout = @http_read_timeout
response = http.request(request)
case response
when Net::HTTPRedirection then
# If we got a redirect request, follow it (if flag set), but don't
# go any deeper (only one redirect supported - don't want to follow
# our tail)
if follow_redirect
redir_uri = URI.parse(response['location'])
response = make_http_request(
Net::HTTP::Get.new(redir_uri.path, false)
)
end
end
# Pick out some useful header info before we return
@jenkins_version = response['X-Jenkins']
@hudson_version = response['X-Hudson']
return response
end | [
"def",
"make_http_request",
"(",
"request",
",",
"follow_redirect",
"=",
"@follow_redirects",
")",
"request",
".",
"basic_auth",
"@username",
",",
"@password",
"if",
"@username",
"request",
"[",
"'Cookie'",
"]",
"=",
"@cookies",
"if",
"@cookies",
"if",
"@proxy_ip",
"case",
"@proxy_protocol",
"when",
"'http'",
"http",
"=",
"Net",
"::",
"HTTP",
"::",
"Proxy",
"(",
"@proxy_ip",
",",
"@proxy_port",
")",
".",
"new",
"(",
"@server_ip",
",",
"@server_port",
")",
"when",
"'socks'",
"http",
"=",
"Net",
"::",
"HTTP",
"::",
"SOCKSProxy",
"(",
"@proxy_ip",
",",
"@proxy_port",
")",
".",
"start",
"(",
"@server_ip",
",",
"@server_port",
")",
"else",
"raise",
"\"unknown proxy protocol: '#{@proxy_protocol}'\"",
"end",
"else",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"@server_ip",
",",
"@server_port",
")",
"end",
"if",
"@ssl",
"&&",
"@pkcs_file_path",
"http",
".",
"use_ssl",
"=",
"true",
"pkcs12",
"=",
"OpenSSL",
"::",
"PKCS12",
".",
"new",
"(",
"File",
".",
"binread",
"(",
"@pkcs_file_path",
")",
",",
"@pass_phrase",
"!=",
"nil",
"?",
"@pass_phrase",
":",
"\"\"",
")",
"http",
".",
"cert",
"=",
"pkcs12",
".",
"certificate",
"http",
".",
"key",
"=",
"pkcs12",
".",
"key",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"elsif",
"@ssl",
"http",
".",
"use_ssl",
"=",
"true",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_PEER",
"http",
".",
"ca_file",
"=",
"@ca_file",
"if",
"@ca_file",
"end",
"http",
".",
"open_timeout",
"=",
"@http_open_timeout",
"http",
".",
"read_timeout",
"=",
"@http_read_timeout",
"response",
"=",
"http",
".",
"request",
"(",
"request",
")",
"case",
"response",
"when",
"Net",
"::",
"HTTPRedirection",
"then",
"# If we got a redirect request, follow it (if flag set), but don't",
"# go any deeper (only one redirect supported - don't want to follow",
"# our tail)",
"if",
"follow_redirect",
"redir_uri",
"=",
"URI",
".",
"parse",
"(",
"response",
"[",
"'location'",
"]",
")",
"response",
"=",
"make_http_request",
"(",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"redir_uri",
".",
"path",
",",
"false",
")",
")",
"end",
"end",
"# Pick out some useful header info before we return",
"@jenkins_version",
"=",
"response",
"[",
"'X-Jenkins'",
"]",
"@hudson_version",
"=",
"response",
"[",
"'X-Hudson'",
"]",
"return",
"response",
"end"
] | Connects to the Jenkins server, sends the specified request and returns
the response.
@param [Net::HTTPRequest] request The request object to send
@param [Boolean] follow_redirect whether to follow redirects or not
@return [Net::HTTPResponse] Response from Jenkins | [
"Connects",
"to",
"the",
"Jenkins",
"server",
"sends",
"the",
"specified",
"request",
"and",
"returns",
"the",
"response",
"."
] | 72f49f2e7ef12d58a0e33856ca91962b2e27709b | https://github.com/arangamani/jenkins_api_client/blob/72f49f2e7ef12d58a0e33856ca91962b2e27709b/lib/jenkins_api_client/client.rb#L339-L390 | train |
arangamani/jenkins_api_client | lib/jenkins_api_client/client.rb | JenkinsApi.Client.api_get_request | def api_get_request(url_prefix, tree = nil, url_suffix ="/api/json",
raw_response = false)
url_prefix = "#{@jenkins_path}#{url_prefix}"
to_get = ""
if tree
to_get = "#{url_prefix}#{url_suffix}?#{tree}"
else
to_get = "#{url_prefix}#{url_suffix}"
end
request = Net::HTTP::Get.new(to_get)
@logger.debug "GET #{to_get}"
response = make_http_request(request)
if raw_response
handle_exception(response, "raw")
else
handle_exception(response, "body", url_suffix =~ /json/)
end
end | ruby | def api_get_request(url_prefix, tree = nil, url_suffix ="/api/json",
raw_response = false)
url_prefix = "#{@jenkins_path}#{url_prefix}"
to_get = ""
if tree
to_get = "#{url_prefix}#{url_suffix}?#{tree}"
else
to_get = "#{url_prefix}#{url_suffix}"
end
request = Net::HTTP::Get.new(to_get)
@logger.debug "GET #{to_get}"
response = make_http_request(request)
if raw_response
handle_exception(response, "raw")
else
handle_exception(response, "body", url_suffix =~ /json/)
end
end | [
"def",
"api_get_request",
"(",
"url_prefix",
",",
"tree",
"=",
"nil",
",",
"url_suffix",
"=",
"\"/api/json\"",
",",
"raw_response",
"=",
"false",
")",
"url_prefix",
"=",
"\"#{@jenkins_path}#{url_prefix}\"",
"to_get",
"=",
"\"\"",
"if",
"tree",
"to_get",
"=",
"\"#{url_prefix}#{url_suffix}?#{tree}\"",
"else",
"to_get",
"=",
"\"#{url_prefix}#{url_suffix}\"",
"end",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"to_get",
")",
"@logger",
".",
"debug",
"\"GET #{to_get}\"",
"response",
"=",
"make_http_request",
"(",
"request",
")",
"if",
"raw_response",
"handle_exception",
"(",
"response",
",",
"\"raw\"",
")",
"else",
"handle_exception",
"(",
"response",
",",
"\"body\"",
",",
"url_suffix",
"=~",
"/",
"/",
")",
"end",
"end"
] | Sends a GET request to the Jenkins CI server with the specified URL
@param [String] url_prefix The prefix to use in the URL
@param [String] tree A specific JSON tree to optimize the API call
@param [String] url_suffix The suffix to be used in the URL
@param [Boolean] raw_response Return complete Response object instead of
JSON body of response
@return [String, Hash] JSON response from Jenkins | [
"Sends",
"a",
"GET",
"request",
"to",
"the",
"Jenkins",
"CI",
"server",
"with",
"the",
"specified",
"URL"
] | 72f49f2e7ef12d58a0e33856ca91962b2e27709b | https://github.com/arangamani/jenkins_api_client/blob/72f49f2e7ef12d58a0e33856ca91962b2e27709b/lib/jenkins_api_client/client.rb#L414-L431 | train |
arangamani/jenkins_api_client | lib/jenkins_api_client/client.rb | JenkinsApi.Client.api_post_request | def api_post_request(url_prefix, form_data = {}, raw_response = false)
retries = @crumb_max_retries
begin
refresh_crumbs
# Added form_data default {} instead of nil to help with proxies
# that barf with empty post
request = Net::HTTP::Post.new("#{@jenkins_path}#{url_prefix}")
@logger.debug "POST #{url_prefix}"
if @crumbs_enabled
request[@crumb["crumbRequestField"]] = @crumb["crumb"]
end
request.set_form_data(form_data)
response = make_http_request(request)
if raw_response
handle_exception(response, "raw")
else
handle_exception(response)
end
rescue Exceptions::ForbiddenException => e
refresh_crumbs(true)
if @crumbs_enabled
@logger.info "Retrying: #{@crumb_max_retries - retries + 1} out of" +
" #{@crumb_max_retries} times..."
retries -= 1
if retries > 0
retry
else
raise Exceptions::ForbiddenWithCrumb.new(@logger, e.message)
end
else
raise
end
end
end | ruby | def api_post_request(url_prefix, form_data = {}, raw_response = false)
retries = @crumb_max_retries
begin
refresh_crumbs
# Added form_data default {} instead of nil to help with proxies
# that barf with empty post
request = Net::HTTP::Post.new("#{@jenkins_path}#{url_prefix}")
@logger.debug "POST #{url_prefix}"
if @crumbs_enabled
request[@crumb["crumbRequestField"]] = @crumb["crumb"]
end
request.set_form_data(form_data)
response = make_http_request(request)
if raw_response
handle_exception(response, "raw")
else
handle_exception(response)
end
rescue Exceptions::ForbiddenException => e
refresh_crumbs(true)
if @crumbs_enabled
@logger.info "Retrying: #{@crumb_max_retries - retries + 1} out of" +
" #{@crumb_max_retries} times..."
retries -= 1
if retries > 0
retry
else
raise Exceptions::ForbiddenWithCrumb.new(@logger, e.message)
end
else
raise
end
end
end | [
"def",
"api_post_request",
"(",
"url_prefix",
",",
"form_data",
"=",
"{",
"}",
",",
"raw_response",
"=",
"false",
")",
"retries",
"=",
"@crumb_max_retries",
"begin",
"refresh_crumbs",
"# Added form_data default {} instead of nil to help with proxies",
"# that barf with empty post",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"\"#{@jenkins_path}#{url_prefix}\"",
")",
"@logger",
".",
"debug",
"\"POST #{url_prefix}\"",
"if",
"@crumbs_enabled",
"request",
"[",
"@crumb",
"[",
"\"crumbRequestField\"",
"]",
"]",
"=",
"@crumb",
"[",
"\"crumb\"",
"]",
"end",
"request",
".",
"set_form_data",
"(",
"form_data",
")",
"response",
"=",
"make_http_request",
"(",
"request",
")",
"if",
"raw_response",
"handle_exception",
"(",
"response",
",",
"\"raw\"",
")",
"else",
"handle_exception",
"(",
"response",
")",
"end",
"rescue",
"Exceptions",
"::",
"ForbiddenException",
"=>",
"e",
"refresh_crumbs",
"(",
"true",
")",
"if",
"@crumbs_enabled",
"@logger",
".",
"info",
"\"Retrying: #{@crumb_max_retries - retries + 1} out of\"",
"+",
"\" #{@crumb_max_retries} times...\"",
"retries",
"-=",
"1",
"if",
"retries",
">",
"0",
"retry",
"else",
"raise",
"Exceptions",
"::",
"ForbiddenWithCrumb",
".",
"new",
"(",
"@logger",
",",
"e",
".",
"message",
")",
"end",
"else",
"raise",
"end",
"end",
"end"
] | Sends a POST message to the Jenkins CI server with the specified URL
@param [String] url_prefix The prefix to be used in the URL
@param [Hash] form_data Form data to send with POST request
@param [Boolean] raw_response Return complete Response object instead of
JSON body of response
@return [String] Response code form Jenkins Response | [
"Sends",
"a",
"POST",
"message",
"to",
"the",
"Jenkins",
"CI",
"server",
"with",
"the",
"specified",
"URL"
] | 72f49f2e7ef12d58a0e33856ca91962b2e27709b | https://github.com/arangamani/jenkins_api_client/blob/72f49f2e7ef12d58a0e33856ca91962b2e27709b/lib/jenkins_api_client/client.rb#L442-L478 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.