id
int32
0
24.9k
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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
11,100
sds/overcommit
lib/overcommit/git_repo.rb
Overcommit.GitRepo.all_files
def all_files `git ls-files`. split(/\n/). map { |relative_file| File.expand_path(relative_file) }. reject { |file| File.directory?(file) } # Exclude submodule directories end
ruby
def all_files `git ls-files`. split(/\n/). map { |relative_file| File.expand_path(relative_file) }. reject { |file| File.directory?(file) } # Exclude submodule directories end
[ "def", "all_files", "`", "`", ".", "split", "(", "/", "\\n", "/", ")", ".", "map", "{", "|", "relative_file", "|", "File", ".", "expand_path", "(", "relative_file", ")", "}", ".", "reject", "{", "|", "file", "|", "File", ".", "directory?", "(", "file", ")", "}", "# Exclude submodule directories", "end" ]
Returns the names of all files that are tracked by git. @return [Array<String>] list of absolute file paths
[ "Returns", "the", "names", "of", "all", "files", "that", "are", "tracked", "by", "git", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/git_repo.rb#L129-L134
11,101
sds/overcommit
lib/overcommit/git_repo.rb
Overcommit.GitRepo.restore_merge_state
def restore_merge_state if @merge_head FileUtils.touch(File.expand_path('MERGE_MODE', Overcommit::Utils.git_dir)) File.open(File.expand_path('MERGE_HEAD', Overcommit::Utils.git_dir), 'w') do |f| f.write(@merge_head) end @merge_head = nil end if @merge_msg File.open(File.expand_path('MERGE_MSG', Overcommit::Utils.git_dir), 'w') do |f| f.write("#{@merge_msg}\n") end @merge_msg = nil end end
ruby
def restore_merge_state if @merge_head FileUtils.touch(File.expand_path('MERGE_MODE', Overcommit::Utils.git_dir)) File.open(File.expand_path('MERGE_HEAD', Overcommit::Utils.git_dir), 'w') do |f| f.write(@merge_head) end @merge_head = nil end if @merge_msg File.open(File.expand_path('MERGE_MSG', Overcommit::Utils.git_dir), 'w') do |f| f.write("#{@merge_msg}\n") end @merge_msg = nil end end
[ "def", "restore_merge_state", "if", "@merge_head", "FileUtils", ".", "touch", "(", "File", ".", "expand_path", "(", "'MERGE_MODE'", ",", "Overcommit", "::", "Utils", ".", "git_dir", ")", ")", "File", ".", "open", "(", "File", ".", "expand_path", "(", "'MERGE_HEAD'", ",", "Overcommit", "::", "Utils", ".", "git_dir", ")", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "@merge_head", ")", "end", "@merge_head", "=", "nil", "end", "if", "@merge_msg", "File", ".", "open", "(", "File", ".", "expand_path", "(", "'MERGE_MSG'", ",", "Overcommit", "::", "Utils", ".", "git_dir", ")", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "\"#{@merge_msg}\\n\"", ")", "end", "@merge_msg", "=", "nil", "end", "end" ]
Restore any relevant files that were present when repo was in the middle of a merge.
[ "Restore", "any", "relevant", "files", "that", "were", "present", "when", "repo", "was", "in", "the", "middle", "of", "a", "merge", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/git_repo.rb#L175-L191
11,102
sds/overcommit
lib/overcommit/git_repo.rb
Overcommit.GitRepo.restore_cherry_pick_state
def restore_cherry_pick_state if @cherry_head File.open(File.expand_path('CHERRY_PICK_HEAD', Overcommit::Utils.git_dir), 'w') do |f| f.write(@cherry_head) end @cherry_head = nil end end
ruby
def restore_cherry_pick_state if @cherry_head File.open(File.expand_path('CHERRY_PICK_HEAD', Overcommit::Utils.git_dir), 'w') do |f| f.write(@cherry_head) end @cherry_head = nil end end
[ "def", "restore_cherry_pick_state", "if", "@cherry_head", "File", ".", "open", "(", "File", ".", "expand_path", "(", "'CHERRY_PICK_HEAD'", ",", "Overcommit", "::", "Utils", ".", "git_dir", ")", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "@cherry_head", ")", "end", "@cherry_head", "=", "nil", "end", "end" ]
Restore any relevant files that were present when repo was in the middle of a cherry-pick.
[ "Restore", "any", "relevant", "files", "that", "were", "present", "when", "repo", "was", "in", "the", "middle", "of", "a", "cherry", "-", "pick", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/git_repo.rb#L195-L203
11,103
sds/overcommit
lib/overcommit/hook_signer.rb
Overcommit.HookSigner.update_signature!
def update_signature! result = Overcommit::Utils.execute( %w[git config --local] + [signature_config_key, signature] ) unless result.success? raise Overcommit::Exceptions::GitConfigError, "Unable to write to local repo git config: #{result.stderr}" end end
ruby
def update_signature! result = Overcommit::Utils.execute( %w[git config --local] + [signature_config_key, signature] ) unless result.success? raise Overcommit::Exceptions::GitConfigError, "Unable to write to local repo git config: #{result.stderr}" end end
[ "def", "update_signature!", "result", "=", "Overcommit", "::", "Utils", ".", "execute", "(", "%w[", "git", "config", "--local", "]", "+", "[", "signature_config_key", ",", "signature", "]", ")", "unless", "result", ".", "success?", "raise", "Overcommit", "::", "Exceptions", "::", "GitConfigError", ",", "\"Unable to write to local repo git config: #{result.stderr}\"", "end", "end" ]
Update the current stored signature for this hook.
[ "Update", "the", "current", "stored", "signature", "for", "this", "hook", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_signer.rb#L69-L78
11,104
sds/overcommit
lib/overcommit/hook_signer.rb
Overcommit.HookSigner.signature
def signature hook_config = @config.for_hook(@hook_name, @context.hook_class_name). dup. tap { |config| IGNORED_CONFIG_KEYS.each { |k| config.delete(k) } } content_to_sign = if signable_file?(hook_path) && Overcommit::GitRepo.tracked?(hook_path) hook_contents end Digest::SHA256.hexdigest(content_to_sign.to_s + hook_config.to_s) end
ruby
def signature hook_config = @config.for_hook(@hook_name, @context.hook_class_name). dup. tap { |config| IGNORED_CONFIG_KEYS.each { |k| config.delete(k) } } content_to_sign = if signable_file?(hook_path) && Overcommit::GitRepo.tracked?(hook_path) hook_contents end Digest::SHA256.hexdigest(content_to_sign.to_s + hook_config.to_s) end
[ "def", "signature", "hook_config", "=", "@config", ".", "for_hook", "(", "@hook_name", ",", "@context", ".", "hook_class_name", ")", ".", "dup", ".", "tap", "{", "|", "config", "|", "IGNORED_CONFIG_KEYS", ".", "each", "{", "|", "k", "|", "config", ".", "delete", "(", "k", ")", "}", "}", "content_to_sign", "=", "if", "signable_file?", "(", "hook_path", ")", "&&", "Overcommit", "::", "GitRepo", ".", "tracked?", "(", "hook_path", ")", "hook_contents", "end", "Digest", "::", "SHA256", ".", "hexdigest", "(", "content_to_sign", ".", "to_s", "+", "hook_config", ".", "to_s", ")", "end" ]
Calculates a hash of a hook using a combination of its configuration and file contents. This way, if either the plugin code changes or its configuration changes, the hash will change and we can alert the user to this change.
[ "Calculates", "a", "hash", "of", "a", "hook", "using", "a", "combination", "of", "its", "configuration", "and", "file", "contents", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_signer.rb#L87-L98
11,105
sds/overcommit
lib/overcommit/printer.rb
Overcommit.Printer.end_hook
def end_hook(hook, status, output) # Want to print the header for quiet hooks only if the result wasn't good # so that the user knows what failed print_header(hook) if (!hook.quiet? && !@config['quiet']) || status != :pass print_result(hook, status, output) end
ruby
def end_hook(hook, status, output) # Want to print the header for quiet hooks only if the result wasn't good # so that the user knows what failed print_header(hook) if (!hook.quiet? && !@config['quiet']) || status != :pass print_result(hook, status, output) end
[ "def", "end_hook", "(", "hook", ",", "status", ",", "output", ")", "# Want to print the header for quiet hooks only if the result wasn't good", "# so that the user knows what failed", "print_header", "(", "hook", ")", "if", "(", "!", "hook", ".", "quiet?", "&&", "!", "@config", "[", "'quiet'", "]", ")", "||", "status", "!=", ":pass", "print_result", "(", "hook", ",", "status", ",", "output", ")", "end" ]
Executed at the end of an individual hook run.
[ "Executed", "at", "the", "end", "of", "an", "individual", "hook", "run", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/printer.rb#L37-L43
11,106
ruby/rake
lib/rake/loaders/makefile.rb
Rake.MakefileLoader.process_line
def process_line(line) # :nodoc: file_tasks, args = line.split(":", 2) return if args.nil? dependents = args.split.map { |d| respace(d) } file_tasks.scan(/\S+/) do |file_task| file_task = respace(file_task) file file_task => dependents end end
ruby
def process_line(line) # :nodoc: file_tasks, args = line.split(":", 2) return if args.nil? dependents = args.split.map { |d| respace(d) } file_tasks.scan(/\S+/) do |file_task| file_task = respace(file_task) file file_task => dependents end end
[ "def", "process_line", "(", "line", ")", "# :nodoc:", "file_tasks", ",", "args", "=", "line", ".", "split", "(", "\":\"", ",", "2", ")", "return", "if", "args", ".", "nil?", "dependents", "=", "args", ".", "split", ".", "map", "{", "|", "d", "|", "respace", "(", "d", ")", "}", "file_tasks", ".", "scan", "(", "/", "\\S", "/", ")", "do", "|", "file_task", "|", "file_task", "=", "respace", "(", "file_task", ")", "file", "file_task", "=>", "dependents", "end", "end" ]
Process one logical line of makefile data.
[ "Process", "one", "logical", "line", "of", "makefile", "data", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/loaders/makefile.rb#L37-L45
11,107
ruby/rake
lib/rake/task.rb
Rake.Task.invoke
def invoke(*args) task_args = TaskArguments.new(arg_names, args) invoke_with_call_chain(task_args, InvocationChain::EMPTY) end
ruby
def invoke(*args) task_args = TaskArguments.new(arg_names, args) invoke_with_call_chain(task_args, InvocationChain::EMPTY) end
[ "def", "invoke", "(", "*", "args", ")", "task_args", "=", "TaskArguments", ".", "new", "(", "arg_names", ",", "args", ")", "invoke_with_call_chain", "(", "task_args", ",", "InvocationChain", "::", "EMPTY", ")", "end" ]
Invoke the task if it is needed. Prerequisites are invoked first.
[ "Invoke", "the", "task", "if", "it", "is", "needed", ".", "Prerequisites", "are", "invoked", "first", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/task.rb#L181-L184
11,108
ruby/rake
lib/rake/task.rb
Rake.Task.transform_comments
def transform_comments(separator, &block) if @comments.empty? nil else block ||= lambda { |c| c } @comments.map(&block).join(separator) end end
ruby
def transform_comments(separator, &block) if @comments.empty? nil else block ||= lambda { |c| c } @comments.map(&block).join(separator) end end
[ "def", "transform_comments", "(", "separator", ",", "&", "block", ")", "if", "@comments", ".", "empty?", "nil", "else", "block", "||=", "lambda", "{", "|", "c", "|", "c", "}", "@comments", ".", "map", "(", "block", ")", ".", "join", "(", "separator", ")", "end", "end" ]
Transform the list of comments as specified by the block and join with the separator.
[ "Transform", "the", "list", "of", "comments", "as", "specified", "by", "the", "block", "and", "join", "with", "the", "separator", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/task.rb#L319-L326
11,109
ruby/rake
lib/rake/file_utils_ext.rb
Rake.FileUtilsExt.rake_merge_option
def rake_merge_option(args, defaults) if Hash === args.last defaults.update(args.last) args.pop end args.push defaults args end
ruby
def rake_merge_option(args, defaults) if Hash === args.last defaults.update(args.last) args.pop end args.push defaults args end
[ "def", "rake_merge_option", "(", "args", ",", "defaults", ")", "if", "Hash", "===", "args", ".", "last", "defaults", ".", "update", "(", "args", ".", "last", ")", "args", ".", "pop", "end", "args", ".", "push", "defaults", "args", "end" ]
Merge the given options with the default values.
[ "Merge", "the", "given", "options", "with", "the", "default", "values", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/file_utils_ext.rb#L117-L124
11,110
ruby/rake
lib/rake/file_utils_ext.rb
Rake.FileUtilsExt.rake_check_options
def rake_check_options(options, *optdecl) h = options.dup optdecl.each do |name| h.delete name end raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless h.empty? end
ruby
def rake_check_options(options, *optdecl) h = options.dup optdecl.each do |name| h.delete name end raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless h.empty? end
[ "def", "rake_check_options", "(", "options", ",", "*", "optdecl", ")", "h", "=", "options", ".", "dup", "optdecl", ".", "each", "do", "|", "name", "|", "h", ".", "delete", "name", "end", "raise", "ArgumentError", ",", "\"no such option: #{h.keys.join(' ')}\"", "unless", "h", ".", "empty?", "end" ]
Check that the options do not contain options not listed in +optdecl+. An ArgumentError exception is thrown if non-declared options are found.
[ "Check", "that", "the", "options", "do", "not", "contain", "options", "not", "listed", "in", "+", "optdecl", "+", ".", "An", "ArgumentError", "exception", "is", "thrown", "if", "non", "-", "declared", "options", "are", "found", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/file_utils_ext.rb#L134-L141
11,111
ruby/rake
lib/rake/scope.rb
Rake.Scope.trim
def trim(n) result = self while n > 0 && !result.empty? result = result.tail n -= 1 end result end
ruby
def trim(n) result = self while n > 0 && !result.empty? result = result.tail n -= 1 end result end
[ "def", "trim", "(", "n", ")", "result", "=", "self", "while", "n", ">", "0", "&&", "!", "result", ".", "empty?", "result", "=", "result", ".", "tail", "n", "-=", "1", "end", "result", "end" ]
Trim +n+ innermost scope levels from the scope. In no case will this trim beyond the toplevel scope.
[ "Trim", "+", "n", "+", "innermost", "scope", "levels", "from", "the", "scope", ".", "In", "no", "case", "will", "this", "trim", "beyond", "the", "toplevel", "scope", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/scope.rb#L17-L24
11,112
ruby/rake
lib/rake/application.rb
Rake.Application.init
def init(app_name="rake", argv = ARGV) standard_exception_handling do @name = app_name begin args = handle_options argv rescue ArgumentError # Backward compatibility for capistrano args = handle_options end collect_command_line_tasks(args) end end
ruby
def init(app_name="rake", argv = ARGV) standard_exception_handling do @name = app_name begin args = handle_options argv rescue ArgumentError # Backward compatibility for capistrano args = handle_options end collect_command_line_tasks(args) end end
[ "def", "init", "(", "app_name", "=", "\"rake\"", ",", "argv", "=", "ARGV", ")", "standard_exception_handling", "do", "@name", "=", "app_name", "begin", "args", "=", "handle_options", "argv", "rescue", "ArgumentError", "# Backward compatibility for capistrano", "args", "=", "handle_options", "end", "collect_command_line_tasks", "(", "args", ")", "end", "end" ]
Initialize the command line parameters and app name.
[ "Initialize", "the", "command", "line", "parameters", "and", "app", "name", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/application.rb#L88-L99
11,113
ruby/rake
lib/rake/application.rb
Rake.Application.have_rakefile
def have_rakefile # :nodoc: @rakefiles.each do |fn| if File.exist?(fn) others = FileList.glob(fn, File::FNM_CASEFOLD) return others.size == 1 ? others.first : fn elsif fn == "" return fn end end return nil end
ruby
def have_rakefile # :nodoc: @rakefiles.each do |fn| if File.exist?(fn) others = FileList.glob(fn, File::FNM_CASEFOLD) return others.size == 1 ? others.first : fn elsif fn == "" return fn end end return nil end
[ "def", "have_rakefile", "# :nodoc:", "@rakefiles", ".", "each", "do", "|", "fn", "|", "if", "File", ".", "exist?", "(", "fn", ")", "others", "=", "FileList", ".", "glob", "(", "fn", ",", "File", "::", "FNM_CASEFOLD", ")", "return", "others", ".", "size", "==", "1", "?", "others", ".", "first", ":", "fn", "elsif", "fn", "==", "\"\"", "return", "fn", "end", "end", "return", "nil", "end" ]
True if one of the files in RAKEFILES is in the current directory. If a match is found, it is copied into @rakefile.
[ "True", "if", "one", "of", "the", "files", "in", "RAKEFILES", "is", "in", "the", "current", "directory", ".", "If", "a", "match", "is", "found", "it", "is", "copied", "into" ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/application.rb#L274-L284
11,114
ruby/rake
lib/rake/file_list.rb
Rake.FileList.sub
def sub(pat, rep) inject(self.class.new) { |res, fn| res << fn.sub(pat, rep) } end
ruby
def sub(pat, rep) inject(self.class.new) { |res, fn| res << fn.sub(pat, rep) } end
[ "def", "sub", "(", "pat", ",", "rep", ")", "inject", "(", "self", ".", "class", ".", "new", ")", "{", "|", "res", ",", "fn", "|", "res", "<<", "fn", ".", "sub", "(", "pat", ",", "rep", ")", "}", "end" ]
Return a new FileList with the results of running +sub+ against each element of the original list. Example: FileList['a.c', 'b.c'].sub(/\.c$/, '.o') => ['a.o', 'b.o']
[ "Return", "a", "new", "FileList", "with", "the", "results", "of", "running", "+", "sub", "+", "against", "each", "element", "of", "the", "original", "list", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/file_list.rb#L242-L244
11,115
ruby/rake
lib/rake/file_list.rb
Rake.FileList.gsub
def gsub(pat, rep) inject(self.class.new) { |res, fn| res << fn.gsub(pat, rep) } end
ruby
def gsub(pat, rep) inject(self.class.new) { |res, fn| res << fn.gsub(pat, rep) } end
[ "def", "gsub", "(", "pat", ",", "rep", ")", "inject", "(", "self", ".", "class", ".", "new", ")", "{", "|", "res", ",", "fn", "|", "res", "<<", "fn", ".", "gsub", "(", "pat", ",", "rep", ")", "}", "end" ]
Return a new FileList with the results of running +gsub+ against each element of the original list. Example: FileList['lib/test/file', 'x/y'].gsub(/\//, "\\") => ['lib\\test\\file', 'x\\y']
[ "Return", "a", "new", "FileList", "with", "the", "results", "of", "running", "+", "gsub", "+", "against", "each", "element", "of", "the", "original", "list", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/file_list.rb#L253-L255
11,116
ruby/rake
lib/rake/file_list.rb
Rake.FileList.sub!
def sub!(pat, rep) each_with_index { |fn, i| self[i] = fn.sub(pat, rep) } self end
ruby
def sub!(pat, rep) each_with_index { |fn, i| self[i] = fn.sub(pat, rep) } self end
[ "def", "sub!", "(", "pat", ",", "rep", ")", "each_with_index", "{", "|", "fn", ",", "i", "|", "self", "[", "i", "]", "=", "fn", ".", "sub", "(", "pat", ",", "rep", ")", "}", "self", "end" ]
Same as +sub+ except that the original file list is modified.
[ "Same", "as", "+", "sub", "+", "except", "that", "the", "original", "file", "list", "is", "modified", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/file_list.rb#L258-L261
11,117
ruby/rake
lib/rake/file_list.rb
Rake.FileList.gsub!
def gsub!(pat, rep) each_with_index { |fn, i| self[i] = fn.gsub(pat, rep) } self end
ruby
def gsub!(pat, rep) each_with_index { |fn, i| self[i] = fn.gsub(pat, rep) } self end
[ "def", "gsub!", "(", "pat", ",", "rep", ")", "each_with_index", "{", "|", "fn", ",", "i", "|", "self", "[", "i", "]", "=", "fn", ".", "gsub", "(", "pat", ",", "rep", ")", "}", "self", "end" ]
Same as +gsub+ except that the original file list is modified.
[ "Same", "as", "+", "gsub", "+", "except", "that", "the", "original", "file", "list", "is", "modified", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/file_list.rb#L264-L267
11,118
ruby/rake
lib/rake/packagetask.rb
Rake.PackageTask.define
def define fail "Version required (or :noversion)" if @version.nil? @version = nil if :noversion == @version desc "Build all the packages" task :package desc "Force a rebuild of the package files" task repackage: [:clobber_package, :package] desc "Remove package products" task :clobber_package do rm_r package_dir rescue nil end task clobber: [:clobber_package] [ [need_tar, tgz_file, "z"], [need_tar_gz, tar_gz_file, "z"], [need_tar_bz2, tar_bz2_file, "j"], [need_tar_xz, tar_xz_file, "J"] ].each do |need, file, flag| if need task package: ["#{package_dir}/#{file}"] file "#{package_dir}/#{file}" => [package_dir_path] + package_files do chdir(package_dir) { sh @tar_command, "#{flag}cvf", file, package_name } end end end if need_zip task package: ["#{package_dir}/#{zip_file}"] file "#{package_dir}/#{zip_file}" => [package_dir_path] + package_files do chdir(package_dir) { sh @zip_command, "-r", zip_file, package_name } end end directory package_dir_path => @package_files do @package_files.each do |fn| f = File.join(package_dir_path, fn) fdir = File.dirname(f) mkdir_p(fdir) unless File.exist?(fdir) if File.directory?(fn) mkdir_p(f) else rm_f f safe_ln(fn, f) end end end self end
ruby
def define fail "Version required (or :noversion)" if @version.nil? @version = nil if :noversion == @version desc "Build all the packages" task :package desc "Force a rebuild of the package files" task repackage: [:clobber_package, :package] desc "Remove package products" task :clobber_package do rm_r package_dir rescue nil end task clobber: [:clobber_package] [ [need_tar, tgz_file, "z"], [need_tar_gz, tar_gz_file, "z"], [need_tar_bz2, tar_bz2_file, "j"], [need_tar_xz, tar_xz_file, "J"] ].each do |need, file, flag| if need task package: ["#{package_dir}/#{file}"] file "#{package_dir}/#{file}" => [package_dir_path] + package_files do chdir(package_dir) { sh @tar_command, "#{flag}cvf", file, package_name } end end end if need_zip task package: ["#{package_dir}/#{zip_file}"] file "#{package_dir}/#{zip_file}" => [package_dir_path] + package_files do chdir(package_dir) { sh @zip_command, "-r", zip_file, package_name } end end directory package_dir_path => @package_files do @package_files.each do |fn| f = File.join(package_dir_path, fn) fdir = File.dirname(f) mkdir_p(fdir) unless File.exist?(fdir) if File.directory?(fn) mkdir_p(f) else rm_f f safe_ln(fn, f) end end end self end
[ "def", "define", "fail", "\"Version required (or :noversion)\"", "if", "@version", ".", "nil?", "@version", "=", "nil", "if", ":noversion", "==", "@version", "desc", "\"Build all the packages\"", "task", ":package", "desc", "\"Force a rebuild of the package files\"", "task", "repackage", ":", "[", ":clobber_package", ",", ":package", "]", "desc", "\"Remove package products\"", "task", ":clobber_package", "do", "rm_r", "package_dir", "rescue", "nil", "end", "task", "clobber", ":", "[", ":clobber_package", "]", "[", "[", "need_tar", ",", "tgz_file", ",", "\"z\"", "]", ",", "[", "need_tar_gz", ",", "tar_gz_file", ",", "\"z\"", "]", ",", "[", "need_tar_bz2", ",", "tar_bz2_file", ",", "\"j\"", "]", ",", "[", "need_tar_xz", ",", "tar_xz_file", ",", "\"J\"", "]", "]", ".", "each", "do", "|", "need", ",", "file", ",", "flag", "|", "if", "need", "task", "package", ":", "[", "\"#{package_dir}/#{file}\"", "]", "file", "\"#{package_dir}/#{file}\"", "=>", "[", "package_dir_path", "]", "+", "package_files", "do", "chdir", "(", "package_dir", ")", "{", "sh", "@tar_command", ",", "\"#{flag}cvf\"", ",", "file", ",", "package_name", "}", "end", "end", "end", "if", "need_zip", "task", "package", ":", "[", "\"#{package_dir}/#{zip_file}\"", "]", "file", "\"#{package_dir}/#{zip_file}\"", "=>", "[", "package_dir_path", "]", "+", "package_files", "do", "chdir", "(", "package_dir", ")", "{", "sh", "@zip_command", ",", "\"-r\"", ",", "zip_file", ",", "package_name", "}", "end", "end", "directory", "package_dir_path", "=>", "@package_files", "do", "@package_files", ".", "each", "do", "|", "fn", "|", "f", "=", "File", ".", "join", "(", "package_dir_path", ",", "fn", ")", "fdir", "=", "File", ".", "dirname", "(", "f", ")", "mkdir_p", "(", "fdir", ")", "unless", "File", ".", "exist?", "(", "fdir", ")", "if", "File", ".", "directory?", "(", "fn", ")", "mkdir_p", "(", "f", ")", "else", "rm_f", "f", "safe_ln", "(", "fn", ",", "f", ")", "end", "end", "end", "self", "end" ]
Create the tasks defined by this task library.
[ "Create", "the", "tasks", "defined", "by", "this", "task", "library", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/packagetask.rb#L108-L162
11,119
ruby/rake
lib/rake/thread_pool.rb
Rake.ThreadPool.join
def join @threads_mon.synchronize do begin stat :joining @join_cond.wait unless @threads.empty? stat :joined rescue Exception => e stat :joined $stderr.puts e $stderr.print "Queue contains #{@queue.size} items. " + "Thread pool contains #{@threads.count} threads\n" $stderr.print "Current Thread #{Thread.current} status = " + "#{Thread.current.status}\n" $stderr.puts e.backtrace.join("\n") @threads.each do |t| $stderr.print "Thread #{t} status = #{t.status}\n" $stderr.puts t.backtrace.join("\n") end raise e end end end
ruby
def join @threads_mon.synchronize do begin stat :joining @join_cond.wait unless @threads.empty? stat :joined rescue Exception => e stat :joined $stderr.puts e $stderr.print "Queue contains #{@queue.size} items. " + "Thread pool contains #{@threads.count} threads\n" $stderr.print "Current Thread #{Thread.current} status = " + "#{Thread.current.status}\n" $stderr.puts e.backtrace.join("\n") @threads.each do |t| $stderr.print "Thread #{t} status = #{t.status}\n" $stderr.puts t.backtrace.join("\n") end raise e end end end
[ "def", "join", "@threads_mon", ".", "synchronize", "do", "begin", "stat", ":joining", "@join_cond", ".", "wait", "unless", "@threads", ".", "empty?", "stat", ":joined", "rescue", "Exception", "=>", "e", "stat", ":joined", "$stderr", ".", "puts", "e", "$stderr", ".", "print", "\"Queue contains #{@queue.size} items. \"", "+", "\"Thread pool contains #{@threads.count} threads\\n\"", "$stderr", ".", "print", "\"Current Thread #{Thread.current} status = \"", "+", "\"#{Thread.current.status}\\n\"", "$stderr", ".", "puts", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "@threads", ".", "each", "do", "|", "t", "|", "$stderr", ".", "print", "\"Thread #{t} status = #{t.status}\\n\"", "$stderr", ".", "puts", "t", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "end", "raise", "e", "end", "end", "end" ]
Waits until the queue of futures is empty and all threads have exited.
[ "Waits", "until", "the", "queue", "of", "futures", "is", "empty", "and", "all", "threads", "have", "exited", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/thread_pool.rb#L44-L65
11,120
ruby/rake
lib/rake/thread_pool.rb
Rake.ThreadPool.process_queue_item
def process_queue_item #:nodoc: return false if @queue.empty? # Even though we just asked if the queue was empty, it # still could have had an item which by this statement # is now gone. For this reason we pass true to Queue#deq # because we will sleep indefinitely if it is empty. promise = @queue.deq(true) stat :dequeued, item_id: promise.object_id promise.work return true rescue ThreadError # this means the queue is empty false end
ruby
def process_queue_item #:nodoc: return false if @queue.empty? # Even though we just asked if the queue was empty, it # still could have had an item which by this statement # is now gone. For this reason we pass true to Queue#deq # because we will sleep indefinitely if it is empty. promise = @queue.deq(true) stat :dequeued, item_id: promise.object_id promise.work return true rescue ThreadError # this means the queue is empty false end
[ "def", "process_queue_item", "#:nodoc:", "return", "false", "if", "@queue", ".", "empty?", "# Even though we just asked if the queue was empty, it", "# still could have had an item which by this statement", "# is now gone. For this reason we pass true to Queue#deq", "# because we will sleep indefinitely if it is empty.", "promise", "=", "@queue", ".", "deq", "(", "true", ")", "stat", ":dequeued", ",", "item_id", ":", "promise", ".", "object_id", "promise", ".", "work", "return", "true", "rescue", "ThreadError", "# this means the queue is empty", "false", "end" ]
processes one item on the queue. Returns true if there was an item to process, false if there was no item
[ "processes", "one", "item", "on", "the", "queue", ".", "Returns", "true", "if", "there", "was", "an", "item", "to", "process", "false", "if", "there", "was", "no", "item" ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/thread_pool.rb#L95-L109
11,121
ruby/rake
lib/rake/task_manager.rb
Rake.TaskManager.resolve_args_without_dependencies
def resolve_args_without_dependencies(args) task_name = args.shift if args.size == 1 && args.first.respond_to?(:to_ary) arg_names = args.first.to_ary else arg_names = args end [task_name, arg_names, []] end
ruby
def resolve_args_without_dependencies(args) task_name = args.shift if args.size == 1 && args.first.respond_to?(:to_ary) arg_names = args.first.to_ary else arg_names = args end [task_name, arg_names, []] end
[ "def", "resolve_args_without_dependencies", "(", "args", ")", "task_name", "=", "args", ".", "shift", "if", "args", ".", "size", "==", "1", "&&", "args", ".", "first", ".", "respond_to?", "(", ":to_ary", ")", "arg_names", "=", "args", ".", "first", ".", "to_ary", "else", "arg_names", "=", "args", "end", "[", "task_name", ",", "arg_names", ",", "[", "]", "]", "end" ]
Resolve task arguments for a task or rule when there are no dependencies declared. The patterns recognized by this argument resolving function are: task :t task :t, [:a]
[ "Resolve", "task", "arguments", "for", "a", "task", "or", "rule", "when", "there", "are", "no", "dependencies", "declared", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/task_manager.rb#L105-L113
11,122
ruby/rake
lib/rake/task_manager.rb
Rake.TaskManager.enhance_with_matching_rule
def enhance_with_matching_rule(task_name, level=0) fail Rake::RuleRecursionOverflowError, "Rule Recursion Too Deep" if level >= 16 @rules.each do |pattern, args, extensions, block| if pattern && pattern.match(task_name) task = attempt_rule(task_name, pattern, args, extensions, block, level) return task if task end end nil rescue Rake::RuleRecursionOverflowError => ex ex.add_target(task_name) fail ex end
ruby
def enhance_with_matching_rule(task_name, level=0) fail Rake::RuleRecursionOverflowError, "Rule Recursion Too Deep" if level >= 16 @rules.each do |pattern, args, extensions, block| if pattern && pattern.match(task_name) task = attempt_rule(task_name, pattern, args, extensions, block, level) return task if task end end nil rescue Rake::RuleRecursionOverflowError => ex ex.add_target(task_name) fail ex end
[ "def", "enhance_with_matching_rule", "(", "task_name", ",", "level", "=", "0", ")", "fail", "Rake", "::", "RuleRecursionOverflowError", ",", "\"Rule Recursion Too Deep\"", "if", "level", ">=", "16", "@rules", ".", "each", "do", "|", "pattern", ",", "args", ",", "extensions", ",", "block", "|", "if", "pattern", "&&", "pattern", ".", "match", "(", "task_name", ")", "task", "=", "attempt_rule", "(", "task_name", ",", "pattern", ",", "args", ",", "extensions", ",", "block", ",", "level", ")", "return", "task", "if", "task", "end", "end", "nil", "rescue", "Rake", "::", "RuleRecursionOverflowError", "=>", "ex", "ex", ".", "add_target", "(", "task_name", ")", "fail", "ex", "end" ]
If a rule can be found that matches the task name, enhance the task with the prerequisites and actions from the rule. Set the source attribute of the task appropriately for the rule. Return the enhanced task or nil of no rule was found.
[ "If", "a", "rule", "can", "be", "found", "that", "matches", "the", "task", "name", "enhance", "the", "task", "with", "the", "prerequisites", "and", "actions", "from", "the", "rule", ".", "Set", "the", "source", "attribute", "of", "the", "task", "appropriately", "for", "the", "rule", ".", "Return", "the", "enhanced", "task", "or", "nil", "of", "no", "rule", "was", "found", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/task_manager.rb#L145-L158
11,123
ruby/rake
lib/rake/task_manager.rb
Rake.TaskManager.find_location
def find_location locations = caller i = 0 while locations[i] return locations[i + 1] if locations[i] =~ /rake\/dsl_definition.rb/ i += 1 end nil end
ruby
def find_location locations = caller i = 0 while locations[i] return locations[i + 1] if locations[i] =~ /rake\/dsl_definition.rb/ i += 1 end nil end
[ "def", "find_location", "locations", "=", "caller", "i", "=", "0", "while", "locations", "[", "i", "]", "return", "locations", "[", "i", "+", "1", "]", "if", "locations", "[", "i", "]", "=~", "/", "\\/", "/", "i", "+=", "1", "end", "nil", "end" ]
Find the location that called into the dsl layer.
[ "Find", "the", "location", "that", "called", "into", "the", "dsl", "layer", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/task_manager.rb#L241-L249
11,124
ruby/rake
lib/rake/task_manager.rb
Rake.TaskManager.attempt_rule
def attempt_rule(task_name, task_pattern, args, extensions, block, level) sources = make_sources(task_name, task_pattern, extensions) prereqs = sources.map { |source| trace_rule level, "Attempting Rule #{task_name} => #{source}" if File.exist?(source) || Rake::Task.task_defined?(source) trace_rule level, "(#{task_name} => #{source} ... EXIST)" source elsif parent = enhance_with_matching_rule(source, level + 1) trace_rule level, "(#{task_name} => #{source} ... ENHANCE)" parent.name else trace_rule level, "(#{task_name} => #{source} ... FAIL)" return nil end } task = FileTask.define_task(task_name, { args => prereqs }, &block) task.sources = prereqs task end
ruby
def attempt_rule(task_name, task_pattern, args, extensions, block, level) sources = make_sources(task_name, task_pattern, extensions) prereqs = sources.map { |source| trace_rule level, "Attempting Rule #{task_name} => #{source}" if File.exist?(source) || Rake::Task.task_defined?(source) trace_rule level, "(#{task_name} => #{source} ... EXIST)" source elsif parent = enhance_with_matching_rule(source, level + 1) trace_rule level, "(#{task_name} => #{source} ... ENHANCE)" parent.name else trace_rule level, "(#{task_name} => #{source} ... FAIL)" return nil end } task = FileTask.define_task(task_name, { args => prereqs }, &block) task.sources = prereqs task end
[ "def", "attempt_rule", "(", "task_name", ",", "task_pattern", ",", "args", ",", "extensions", ",", "block", ",", "level", ")", "sources", "=", "make_sources", "(", "task_name", ",", "task_pattern", ",", "extensions", ")", "prereqs", "=", "sources", ".", "map", "{", "|", "source", "|", "trace_rule", "level", ",", "\"Attempting Rule #{task_name} => #{source}\"", "if", "File", ".", "exist?", "(", "source", ")", "||", "Rake", "::", "Task", ".", "task_defined?", "(", "source", ")", "trace_rule", "level", ",", "\"(#{task_name} => #{source} ... EXIST)\"", "source", "elsif", "parent", "=", "enhance_with_matching_rule", "(", "source", ",", "level", "+", "1", ")", "trace_rule", "level", ",", "\"(#{task_name} => #{source} ... ENHANCE)\"", "parent", ".", "name", "else", "trace_rule", "level", ",", "\"(#{task_name} => #{source} ... FAIL)\"", "return", "nil", "end", "}", "task", "=", "FileTask", ".", "define_task", "(", "task_name", ",", "{", "args", "=>", "prereqs", "}", ",", "block", ")", "task", ".", "sources", "=", "prereqs", "task", "end" ]
Attempt to create a rule given the list of prerequisites.
[ "Attempt", "to", "create", "a", "rule", "given", "the", "list", "of", "prerequisites", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/task_manager.rb#L264-L282
11,125
ruby/rake
lib/rake/file_task.rb
Rake.FileTask.out_of_date?
def out_of_date?(stamp) all_prerequisite_tasks.any? { |prereq| prereq_task = application[prereq, @scope] if prereq_task.instance_of?(Rake::FileTask) prereq_task.timestamp > stamp || @application.options.build_all else prereq_task.timestamp > stamp end } end
ruby
def out_of_date?(stamp) all_prerequisite_tasks.any? { |prereq| prereq_task = application[prereq, @scope] if prereq_task.instance_of?(Rake::FileTask) prereq_task.timestamp > stamp || @application.options.build_all else prereq_task.timestamp > stamp end } end
[ "def", "out_of_date?", "(", "stamp", ")", "all_prerequisite_tasks", ".", "any?", "{", "|", "prereq", "|", "prereq_task", "=", "application", "[", "prereq", ",", "@scope", "]", "if", "prereq_task", ".", "instance_of?", "(", "Rake", "::", "FileTask", ")", "prereq_task", ".", "timestamp", ">", "stamp", "||", "@application", ".", "options", ".", "build_all", "else", "prereq_task", ".", "timestamp", ">", "stamp", "end", "}", "end" ]
Are there any prerequisites with a later time than the given time stamp?
[ "Are", "there", "any", "prerequisites", "with", "a", "later", "time", "than", "the", "given", "time", "stamp?" ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/file_task.rb#L32-L41
11,126
ruby/rake
lib/rake/task_arguments.rb
Rake.TaskArguments.new_scope
def new_scope(names) values = names.map { |n| self[n] } self.class.new(names, values + extras, self) end
ruby
def new_scope(names) values = names.map { |n| self[n] } self.class.new(names, values + extras, self) end
[ "def", "new_scope", "(", "names", ")", "values", "=", "names", ".", "map", "{", "|", "n", "|", "self", "[", "n", "]", "}", "self", ".", "class", ".", "new", "(", "names", ",", "values", "+", "extras", ",", "self", ")", "end" ]
Create a new argument scope using the prerequisite argument names.
[ "Create", "a", "new", "argument", "scope", "using", "the", "prerequisite", "argument", "names", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/task_arguments.rb#L38-L41
11,127
ruby/rake
lib/rake/promise.rb
Rake.Promise.work
def work stat :attempting_lock_on, item_id: object_id if @mutex.try_lock stat :has_lock_on, item_id: object_id chore stat :releasing_lock_on, item_id: object_id @mutex.unlock else stat :bailed_on, item_id: object_id end end
ruby
def work stat :attempting_lock_on, item_id: object_id if @mutex.try_lock stat :has_lock_on, item_id: object_id chore stat :releasing_lock_on, item_id: object_id @mutex.unlock else stat :bailed_on, item_id: object_id end end
[ "def", "work", "stat", ":attempting_lock_on", ",", "item_id", ":", "object_id", "if", "@mutex", ".", "try_lock", "stat", ":has_lock_on", ",", "item_id", ":", "object_id", "chore", "stat", ":releasing_lock_on", ",", "item_id", ":", "object_id", "@mutex", ".", "unlock", "else", "stat", ":bailed_on", ",", "item_id", ":", "object_id", "end", "end" ]
If no one else is working this promise, go ahead and do the chore.
[ "If", "no", "one", "else", "is", "working", "this", "promise", "go", "ahead", "and", "do", "the", "chore", "." ]
1c22b490ee6cb8bd614fa8d0d6145f671466206b
https://github.com/ruby/rake/blob/1c22b490ee6cb8bd614fa8d0d6145f671466206b/lib/rake/promise.rb#L42-L52
11,128
cloudfoundry/bosh
src/bosh_common/lib/common/retryable.rb
Bosh.Retryable.retryer
def retryer(&blk) loop do @try_count += 1 y = blk.call(@try_count, @retry_exception) @retry_exception = nil # no exception was raised in the block return y if y raise Bosh::Common::RetryCountExceeded if @try_count >= @retry_limit wait end rescue Exception => exception raise unless @matchers.any? { |m| m.matches?(exception) } raise unless exception.message =~ @matching raise if @try_count >= @retry_limit @retry_exception = exception wait retry ensure @ensure_callback.call(@try_count) end
ruby
def retryer(&blk) loop do @try_count += 1 y = blk.call(@try_count, @retry_exception) @retry_exception = nil # no exception was raised in the block return y if y raise Bosh::Common::RetryCountExceeded if @try_count >= @retry_limit wait end rescue Exception => exception raise unless @matchers.any? { |m| m.matches?(exception) } raise unless exception.message =~ @matching raise if @try_count >= @retry_limit @retry_exception = exception wait retry ensure @ensure_callback.call(@try_count) end
[ "def", "retryer", "(", "&", "blk", ")", "loop", "do", "@try_count", "+=", "1", "y", "=", "blk", ".", "call", "(", "@try_count", ",", "@retry_exception", ")", "@retry_exception", "=", "nil", "# no exception was raised in the block", "return", "y", "if", "y", "raise", "Bosh", "::", "Common", "::", "RetryCountExceeded", "if", "@try_count", ">=", "@retry_limit", "wait", "end", "rescue", "Exception", "=>", "exception", "raise", "unless", "@matchers", ".", "any?", "{", "|", "m", "|", "m", ".", "matches?", "(", "exception", ")", "}", "raise", "unless", "exception", ".", "message", "=~", "@matching", "raise", "if", "@try_count", ">=", "@retry_limit", "@retry_exception", "=", "exception", "wait", "retry", "ensure", "@ensure_callback", ".", "call", "(", "@try_count", ")", "end" ]
Loops until the block returns a true value
[ "Loops", "until", "the", "block", "returns", "a", "true", "value" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh_common/lib/common/retryable.rb#L25-L44
11,129
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/dns/power_dns_manager.rb
Bosh::Director.PowerDnsManager.flush_dns_cache
def flush_dns_cache if @flush_command && !@flush_command.empty? stdout, stderr, status = Open3.capture3(@flush_command) if status == 0 @logger.debug("Flushed #{stdout.chomp} records from DNS cache") else @logger.warn("Failed to flush DNS cache: #{stderr.chomp}") end end end
ruby
def flush_dns_cache if @flush_command && !@flush_command.empty? stdout, stderr, status = Open3.capture3(@flush_command) if status == 0 @logger.debug("Flushed #{stdout.chomp} records from DNS cache") else @logger.warn("Failed to flush DNS cache: #{stderr.chomp}") end end end
[ "def", "flush_dns_cache", "if", "@flush_command", "&&", "!", "@flush_command", ".", "empty?", "stdout", ",", "stderr", ",", "status", "=", "Open3", ".", "capture3", "(", "@flush_command", ")", "if", "status", "==", "0", "@logger", ".", "debug", "(", "\"Flushed #{stdout.chomp} records from DNS cache\"", ")", "else", "@logger", ".", "warn", "(", "\"Failed to flush DNS cache: #{stderr.chomp}\"", ")", "end", "end", "end" ]
Purge cached DNS records
[ "Purge", "cached", "DNS", "records" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/dns/power_dns_manager.rb#L101-L110
11,130
cloudfoundry/bosh
src/spec/support/director.rb
Bosh::Spec.Director.instance
def instance(instance_group_name, index_or_id, options = { deployment_name: Deployments::DEFAULT_DEPLOYMENT_NAME }) find_instance(instances(options), instance_group_name, index_or_id) end
ruby
def instance(instance_group_name, index_or_id, options = { deployment_name: Deployments::DEFAULT_DEPLOYMENT_NAME }) find_instance(instances(options), instance_group_name, index_or_id) end
[ "def", "instance", "(", "instance_group_name", ",", "index_or_id", ",", "options", "=", "{", "deployment_name", ":", "Deployments", "::", "DEFAULT_DEPLOYMENT_NAME", "}", ")", "find_instance", "(", "instances", "(", "options", ")", ",", "instance_group_name", ",", "index_or_id", ")", "end" ]
vm always returns a vm
[ "vm", "always", "returns", "a", "vm" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/spec/support/director.rb#L61-L63
11,131
cloudfoundry/bosh
src/bosh-monitor/lib/bosh/monitor/deployment.rb
Bosh::Monitor.Deployment.upsert_agent
def upsert_agent(instance) @logger.info("Adding agent #{instance.agent_id} (#{instance.job}/#{instance.id}) to #{name}...") agent_id = instance.agent_id if agent_id.nil? @logger.warn("No agent id for instance #{instance.job}/#{instance.id} in deployment #{name}") #count agents for instances with deleted vm, which expect to have vm if instance.expects_vm? && !instance.has_vm? agent = Agent.new("agent_with_no_vm", deployment: name) @instance_id_to_agent[instance.id] = agent agent.update_instance(instance) end return false end # Idle VMs, we don't care about them, but we still want to track them if instance.job.nil? @logger.debug("VM with no job found: #{agent_id}") end agent = @agent_id_to_agent[agent_id] if agent.nil? @logger.debug("Discovered agent #{agent_id}") agent = Agent.new(agent_id, deployment: name) @agent_id_to_agent[agent_id] = agent @instance_id_to_agent.delete(instance.id) if @instance_id_to_agent[instance.id] end agent.update_instance(instance) true end
ruby
def upsert_agent(instance) @logger.info("Adding agent #{instance.agent_id} (#{instance.job}/#{instance.id}) to #{name}...") agent_id = instance.agent_id if agent_id.nil? @logger.warn("No agent id for instance #{instance.job}/#{instance.id} in deployment #{name}") #count agents for instances with deleted vm, which expect to have vm if instance.expects_vm? && !instance.has_vm? agent = Agent.new("agent_with_no_vm", deployment: name) @instance_id_to_agent[instance.id] = agent agent.update_instance(instance) end return false end # Idle VMs, we don't care about them, but we still want to track them if instance.job.nil? @logger.debug("VM with no job found: #{agent_id}") end agent = @agent_id_to_agent[agent_id] if agent.nil? @logger.debug("Discovered agent #{agent_id}") agent = Agent.new(agent_id, deployment: name) @agent_id_to_agent[agent_id] = agent @instance_id_to_agent.delete(instance.id) if @instance_id_to_agent[instance.id] end agent.update_instance(instance) true end
[ "def", "upsert_agent", "(", "instance", ")", "@logger", ".", "info", "(", "\"Adding agent #{instance.agent_id} (#{instance.job}/#{instance.id}) to #{name}...\"", ")", "agent_id", "=", "instance", ".", "agent_id", "if", "agent_id", ".", "nil?", "@logger", ".", "warn", "(", "\"No agent id for instance #{instance.job}/#{instance.id} in deployment #{name}\"", ")", "#count agents for instances with deleted vm, which expect to have vm", "if", "instance", ".", "expects_vm?", "&&", "!", "instance", ".", "has_vm?", "agent", "=", "Agent", ".", "new", "(", "\"agent_with_no_vm\"", ",", "deployment", ":", "name", ")", "@instance_id_to_agent", "[", "instance", ".", "id", "]", "=", "agent", "agent", ".", "update_instance", "(", "instance", ")", "end", "return", "false", "end", "# Idle VMs, we don't care about them, but we still want to track them", "if", "instance", ".", "job", ".", "nil?", "@logger", ".", "debug", "(", "\"VM with no job found: #{agent_id}\"", ")", "end", "agent", "=", "@agent_id_to_agent", "[", "agent_id", "]", "if", "agent", ".", "nil?", "@logger", ".", "debug", "(", "\"Discovered agent #{agent_id}\"", ")", "agent", "=", "Agent", ".", "new", "(", "agent_id", ",", "deployment", ":", "name", ")", "@agent_id_to_agent", "[", "agent_id", "]", "=", "agent", "@instance_id_to_agent", ".", "delete", "(", "instance", ".", "id", ")", "if", "@instance_id_to_agent", "[", "instance", ".", "id", "]", "end", "agent", ".", "update_instance", "(", "instance", ")", "true", "end" ]
Processes VM data from BOSH Director, extracts relevant agent data, wraps it into Agent object and adds it to a list of managed agents.
[ "Processes", "VM", "data", "from", "BOSH", "Director", "extracts", "relevant", "agent", "data", "wraps", "it", "into", "Agent", "object", "and", "adds", "it", "to", "a", "list", "of", "managed", "agents", "." ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-monitor/lib/bosh/monitor/deployment.rb#L63-L96
11,132
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/nats_rpc.rb
Bosh::Director.NatsRpc.subscribe_inbox
def subscribe_inbox # double-check locking to reduce synchronization if @subject_id.nil? # nats lazy-load needs to be outside the synchronized block client = nats @lock.synchronize do if @subject_id.nil? @subject_id = client.subscribe("#{@inbox_name}.>") do |message, _, subject| @handled_response = true handle_response(message, subject) end end end end end
ruby
def subscribe_inbox # double-check locking to reduce synchronization if @subject_id.nil? # nats lazy-load needs to be outside the synchronized block client = nats @lock.synchronize do if @subject_id.nil? @subject_id = client.subscribe("#{@inbox_name}.>") do |message, _, subject| @handled_response = true handle_response(message, subject) end end end end end
[ "def", "subscribe_inbox", "# double-check locking to reduce synchronization", "if", "@subject_id", ".", "nil?", "# nats lazy-load needs to be outside the synchronized block", "client", "=", "nats", "@lock", ".", "synchronize", "do", "if", "@subject_id", ".", "nil?", "@subject_id", "=", "client", ".", "subscribe", "(", "\"#{@inbox_name}.>\"", ")", "do", "|", "message", ",", "_", ",", "subject", "|", "@handled_response", "=", "true", "handle_response", "(", "message", ",", "subject", ")", "end", "end", "end", "end", "end" ]
subscribe to an inbox, if not already subscribed
[ "subscribe", "to", "an", "inbox", "if", "not", "already", "subscribed" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/nats_rpc.rb#L114-L128
11,133
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/compiled_package_requirement.rb
Bosh::Director.CompiledPackageRequirement.dependency_spec
def dependency_spec spec = {} @dependencies.each do |dependency| unless dependency.compiled? raise DirectorError, 'Cannot generate package dependency spec ' \ "for '#{@package.name}', " \ "'#{dependency.package.name}' hasn't been compiled yet" end compiled_package = dependency.compiled_package spec[compiled_package.name] = { 'name' => compiled_package.name, 'version' => "#{compiled_package.version}.#{compiled_package.build}", 'sha1' => compiled_package.sha1, 'blobstore_id' => compiled_package.blobstore_id, } end spec end
ruby
def dependency_spec spec = {} @dependencies.each do |dependency| unless dependency.compiled? raise DirectorError, 'Cannot generate package dependency spec ' \ "for '#{@package.name}', " \ "'#{dependency.package.name}' hasn't been compiled yet" end compiled_package = dependency.compiled_package spec[compiled_package.name] = { 'name' => compiled_package.name, 'version' => "#{compiled_package.version}.#{compiled_package.build}", 'sha1' => compiled_package.sha1, 'blobstore_id' => compiled_package.blobstore_id, } end spec end
[ "def", "dependency_spec", "spec", "=", "{", "}", "@dependencies", ".", "each", "do", "|", "dependency", "|", "unless", "dependency", ".", "compiled?", "raise", "DirectorError", ",", "'Cannot generate package dependency spec '", "\"for '#{@package.name}', \"", "\"'#{dependency.package.name}' hasn't been compiled yet\"", "end", "compiled_package", "=", "dependency", ".", "compiled_package", "spec", "[", "compiled_package", ".", "name", "]", "=", "{", "'name'", "=>", "compiled_package", ".", "name", ",", "'version'", "=>", "\"#{compiled_package.version}.#{compiled_package.build}\"", ",", "'sha1'", "=>", "compiled_package", ".", "sha1", ",", "'blobstore_id'", "=>", "compiled_package", ".", "blobstore_id", ",", "}", "end", "spec", "end" ]
This call only makes sense if all dependencies have already been compiled, otherwise it raises an exception @return [Hash] Hash representation of all package dependencies. Agent uses that to download package dependencies before compiling the package on a compilation VM.
[ "This", "call", "only", "makes", "sense", "if", "all", "dependencies", "have", "already", "been", "compiled", "otherwise", "it", "raises", "an", "exception" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/compiled_package_requirement.rb#L107-L129
11,134
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/agent_client.rb
Bosh::Director.AgentClient.format_exception
def format_exception(exception) return exception.to_s unless exception.is_a?(Hash) msg = exception['message'].to_s if exception['backtrace'] msg += "\n" msg += Array(exception['backtrace']).join("\n") end if exception['blobstore_id'] blob = download_and_delete_blob(exception['blobstore_id']) msg += "\n" msg += blob.to_s end msg end
ruby
def format_exception(exception) return exception.to_s unless exception.is_a?(Hash) msg = exception['message'].to_s if exception['backtrace'] msg += "\n" msg += Array(exception['backtrace']).join("\n") end if exception['blobstore_id'] blob = download_and_delete_blob(exception['blobstore_id']) msg += "\n" msg += blob.to_s end msg end
[ "def", "format_exception", "(", "exception", ")", "return", "exception", ".", "to_s", "unless", "exception", ".", "is_a?", "(", "Hash", ")", "msg", "=", "exception", "[", "'message'", "]", ".", "to_s", "if", "exception", "[", "'backtrace'", "]", "msg", "+=", "\"\\n\"", "msg", "+=", "Array", "(", "exception", "[", "'backtrace'", "]", ")", ".", "join", "(", "\"\\n\"", ")", "end", "if", "exception", "[", "'blobstore_id'", "]", "blob", "=", "download_and_delete_blob", "(", "exception", "[", "'blobstore_id'", "]", ")", "msg", "+=", "\"\\n\"", "msg", "+=", "blob", ".", "to_s", "end", "msg", "end" ]
Returns formatted exception information @param [Hash|#to_s] exception Serialized exception @return [String]
[ "Returns", "formatted", "exception", "information" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/agent_client.rb#L287-L304
11,135
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/agent_client.rb
Bosh::Director.AgentClient.inject_compile_log
def inject_compile_log(response) if response['value'] && response['value'].is_a?(Hash) && response['value']['result'].is_a?(Hash) && blob_id = response['value']['result']['compile_log_id'] compile_log = download_and_delete_blob(blob_id) response['value']['result']['compile_log'] = compile_log end end
ruby
def inject_compile_log(response) if response['value'] && response['value'].is_a?(Hash) && response['value']['result'].is_a?(Hash) && blob_id = response['value']['result']['compile_log_id'] compile_log = download_and_delete_blob(blob_id) response['value']['result']['compile_log'] = compile_log end end
[ "def", "inject_compile_log", "(", "response", ")", "if", "response", "[", "'value'", "]", "&&", "response", "[", "'value'", "]", ".", "is_a?", "(", "Hash", ")", "&&", "response", "[", "'value'", "]", "[", "'result'", "]", ".", "is_a?", "(", "Hash", ")", "&&", "blob_id", "=", "response", "[", "'value'", "]", "[", "'result'", "]", "[", "'compile_log_id'", "]", "compile_log", "=", "download_and_delete_blob", "(", "blob_id", ")", "response", "[", "'value'", "]", "[", "'result'", "]", "[", "'compile_log'", "]", "=", "compile_log", "end", "end" ]
the blob is removed from the blobstore once we have fetched it, but if there is a crash before it is injected into the response and then logged, there is a chance that we lose it
[ "the", "blob", "is", "removed", "from", "the", "blobstore", "once", "we", "have", "fetched", "it", "but", "if", "there", "is", "a", "crash", "before", "it", "is", "injected", "into", "the", "response", "and", "then", "logged", "there", "is", "a", "chance", "that", "we", "lose", "it" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/agent_client.rb#L311-L318
11,136
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/download_helper.rb
Bosh::Director.DownloadHelper.download_remote_file
def download_remote_file(resource, remote_file, local_file, num_redirects = 0) @logger.info("Downloading remote #{resource} from #{remote_file}") if @logger uri = URI.parse(remote_file) req = Net::HTTP::Get.new(uri) if uri.user && uri.password req.basic_auth uri.user, uri.password end Net::HTTP.start(uri.host, uri.port, :ENV, :use_ssl => uri.scheme == 'https') do |http| http.request req do |response| case response when Net::HTTPSuccess File.open(local_file, 'wb') do |file| response.read_body do |chunk| file.write(chunk) end end when Net::HTTPFound, Net::HTTPMovedPermanently raise ResourceError, "Too many redirects at '#{remote_file}'." if num_redirects >= 9 location = response.header['location'] raise ResourceError, "No location header for redirect found at '#{remote_file}'." if location.nil? location = URI.join(uri, location).to_s download_remote_file(resource, location, local_file, num_redirects + 1) when Net::HTTPNotFound @logger.error("Downloading remote #{resource} from #{remote_file} failed: #{response.message}") if @logger raise ResourceNotFound, "No #{resource} found at '#{remote_file}'." else @logger.error("Downloading remote #{resource} from #{remote_file} failed: #{response.message}") if @logger raise ResourceError, "Downloading remote #{resource} failed. Check task debug log for details." end end end rescue URI::Error, SocketError, ::Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e @logger.error("Downloading remote #{resource} from #{remote_file} failed: #{e.inspect}") if @logger raise ResourceError, "Downloading remote #{resource} failed. Check task debug log for details." end
ruby
def download_remote_file(resource, remote_file, local_file, num_redirects = 0) @logger.info("Downloading remote #{resource} from #{remote_file}") if @logger uri = URI.parse(remote_file) req = Net::HTTP::Get.new(uri) if uri.user && uri.password req.basic_auth uri.user, uri.password end Net::HTTP.start(uri.host, uri.port, :ENV, :use_ssl => uri.scheme == 'https') do |http| http.request req do |response| case response when Net::HTTPSuccess File.open(local_file, 'wb') do |file| response.read_body do |chunk| file.write(chunk) end end when Net::HTTPFound, Net::HTTPMovedPermanently raise ResourceError, "Too many redirects at '#{remote_file}'." if num_redirects >= 9 location = response.header['location'] raise ResourceError, "No location header for redirect found at '#{remote_file}'." if location.nil? location = URI.join(uri, location).to_s download_remote_file(resource, location, local_file, num_redirects + 1) when Net::HTTPNotFound @logger.error("Downloading remote #{resource} from #{remote_file} failed: #{response.message}") if @logger raise ResourceNotFound, "No #{resource} found at '#{remote_file}'." else @logger.error("Downloading remote #{resource} from #{remote_file} failed: #{response.message}") if @logger raise ResourceError, "Downloading remote #{resource} failed. Check task debug log for details." end end end rescue URI::Error, SocketError, ::Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e @logger.error("Downloading remote #{resource} from #{remote_file} failed: #{e.inspect}") if @logger raise ResourceError, "Downloading remote #{resource} failed. Check task debug log for details." end
[ "def", "download_remote_file", "(", "resource", ",", "remote_file", ",", "local_file", ",", "num_redirects", "=", "0", ")", "@logger", ".", "info", "(", "\"Downloading remote #{resource} from #{remote_file}\"", ")", "if", "@logger", "uri", "=", "URI", ".", "parse", "(", "remote_file", ")", "req", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ")", "if", "uri", ".", "user", "&&", "uri", ".", "password", "req", ".", "basic_auth", "uri", ".", "user", ",", "uri", ".", "password", "end", "Net", "::", "HTTP", ".", "start", "(", "uri", ".", "host", ",", "uri", ".", "port", ",", ":ENV", ",", ":use_ssl", "=>", "uri", ".", "scheme", "==", "'https'", ")", "do", "|", "http", "|", "http", ".", "request", "req", "do", "|", "response", "|", "case", "response", "when", "Net", "::", "HTTPSuccess", "File", ".", "open", "(", "local_file", ",", "'wb'", ")", "do", "|", "file", "|", "response", ".", "read_body", "do", "|", "chunk", "|", "file", ".", "write", "(", "chunk", ")", "end", "end", "when", "Net", "::", "HTTPFound", ",", "Net", "::", "HTTPMovedPermanently", "raise", "ResourceError", ",", "\"Too many redirects at '#{remote_file}'.\"", "if", "num_redirects", ">=", "9", "location", "=", "response", ".", "header", "[", "'location'", "]", "raise", "ResourceError", ",", "\"No location header for redirect found at '#{remote_file}'.\"", "if", "location", ".", "nil?", "location", "=", "URI", ".", "join", "(", "uri", ",", "location", ")", ".", "to_s", "download_remote_file", "(", "resource", ",", "location", ",", "local_file", ",", "num_redirects", "+", "1", ")", "when", "Net", "::", "HTTPNotFound", "@logger", ".", "error", "(", "\"Downloading remote #{resource} from #{remote_file} failed: #{response.message}\"", ")", "if", "@logger", "raise", "ResourceNotFound", ",", "\"No #{resource} found at '#{remote_file}'.\"", "else", "@logger", ".", "error", "(", "\"Downloading remote #{resource} from #{remote_file} failed: #{response.message}\"", ")", "if", "@logger", "raise", "ResourceError", ",", "\"Downloading remote #{resource} failed. Check task debug log for details.\"", "end", "end", "end", "rescue", "URI", "::", "Error", ",", "SocketError", ",", "::", "Timeout", "::", "Error", ",", "Errno", "::", "EINVAL", ",", "Errno", "::", "ECONNRESET", ",", "Errno", "::", "ECONNREFUSED", ",", "EOFError", ",", "Net", "::", "HTTPBadResponse", ",", "Net", "::", "HTTPHeaderSyntaxError", ",", "Net", "::", "ProtocolError", "=>", "e", "@logger", ".", "error", "(", "\"Downloading remote #{resource} from #{remote_file} failed: #{e.inspect}\"", ")", "if", "@logger", "raise", "ResourceError", ",", "\"Downloading remote #{resource} failed. Check task debug log for details.\"", "end" ]
Downloads a remote file @param [String] resource Resource name to be logged @param [String] remote_file Remote file to download @param [String] local_file Local file to store the downloaded file @raise [Bosh::Director::ResourceNotFound] If remote file is not found @raise [Bosh::Director::ResourceError] If there's a network problem
[ "Downloads", "a", "remote", "file" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/download_helper.rb#L13-L55
11,137
cloudfoundry/bosh
src/bosh-registry/lib/bosh/registry/instance_manager.rb
Bosh::Registry.InstanceManager.update_settings
def update_settings(instance_id, settings) params = { :instance_id => instance_id } instance = Models::RegistryInstance[params] || Models::RegistryInstance.new(params) instance.settings = settings instance.save end
ruby
def update_settings(instance_id, settings) params = { :instance_id => instance_id } instance = Models::RegistryInstance[params] || Models::RegistryInstance.new(params) instance.settings = settings instance.save end
[ "def", "update_settings", "(", "instance_id", ",", "settings", ")", "params", "=", "{", ":instance_id", "=>", "instance_id", "}", "instance", "=", "Models", "::", "RegistryInstance", "[", "params", "]", "||", "Models", "::", "RegistryInstance", ".", "new", "(", "params", ")", "instance", ".", "settings", "=", "settings", "instance", ".", "save", "end" ]
Updates instance settings @param [String] instance_id instance id (instance record will be created in DB if it doesn't already exist) @param [String] settings New settings for the instance
[ "Updates", "instance", "settings" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-registry/lib/bosh/registry/instance_manager.rb#L10-L18
11,138
cloudfoundry/bosh
src/bosh-registry/lib/bosh/registry/instance_manager.rb
Bosh::Registry.InstanceManager.read_settings
def read_settings(instance_id, remote_ip = nil) check_instance_ips(remote_ip, instance_id) if remote_ip get_instance(instance_id).settings end
ruby
def read_settings(instance_id, remote_ip = nil) check_instance_ips(remote_ip, instance_id) if remote_ip get_instance(instance_id).settings end
[ "def", "read_settings", "(", "instance_id", ",", "remote_ip", "=", "nil", ")", "check_instance_ips", "(", "remote_ip", ",", "instance_id", ")", "if", "remote_ip", "get_instance", "(", "instance_id", ")", ".", "settings", "end" ]
Reads instance settings @param [String] instance_id instance id @param [optional, String] remote_ip If this IP is provided, check will be performed to see if it instance id actually has this IP address according to the IaaS.
[ "Reads", "instance", "settings" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-registry/lib/bosh/registry/instance_manager.rb#L26-L30
11,139
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/links/links_manager.rb
Bosh::Director::Links.LinksManager.find_or_create_provider_intent
def find_or_create_provider_intent(link_provider:, link_original_name:, link_type:) intent = Bosh::Director::Models::Links::LinkProviderIntent.find( link_provider: link_provider, original_name: link_original_name, ) if intent.nil? intent = Bosh::Director::Models::Links::LinkProviderIntent.create( link_provider: link_provider, original_name: link_original_name, type: link_type, ) else intent.type = link_type end intent.serial_id = @serial_id if intent.serial_id != @serial_id intent.save end
ruby
def find_or_create_provider_intent(link_provider:, link_original_name:, link_type:) intent = Bosh::Director::Models::Links::LinkProviderIntent.find( link_provider: link_provider, original_name: link_original_name, ) if intent.nil? intent = Bosh::Director::Models::Links::LinkProviderIntent.create( link_provider: link_provider, original_name: link_original_name, type: link_type, ) else intent.type = link_type end intent.serial_id = @serial_id if intent.serial_id != @serial_id intent.save end
[ "def", "find_or_create_provider_intent", "(", "link_provider", ":", ",", "link_original_name", ":", ",", "link_type", ":", ")", "intent", "=", "Bosh", "::", "Director", "::", "Models", "::", "Links", "::", "LinkProviderIntent", ".", "find", "(", "link_provider", ":", "link_provider", ",", "original_name", ":", "link_original_name", ",", ")", "if", "intent", ".", "nil?", "intent", "=", "Bosh", "::", "Director", "::", "Models", "::", "Links", "::", "LinkProviderIntent", ".", "create", "(", "link_provider", ":", "link_provider", ",", "original_name", ":", "link_original_name", ",", "type", ":", "link_type", ",", ")", "else", "intent", ".", "type", "=", "link_type", "end", "intent", ".", "serial_id", "=", "@serial_id", "if", "intent", ".", "serial_id", "!=", "@serial_id", "intent", ".", "save", "end" ]
Used by provider, not using alias because want to update existing provider intent when alias changes
[ "Used", "by", "provider", "not", "using", "alias", "because", "want", "to", "update", "existing", "provider", "intent", "when", "alias", "changes" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/links/links_manager.rb#L46-L64
11,140
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/links/links_manager.rb
Bosh::Director::Links.LinksManager.consumer?
def consumer?(provider_intent, deployment_plan) return true if provider_intent.shared link_consumers = deployment_plan.model.link_consumers link_consumers = link_consumers.select do |consumer| consumer.serial_id == @serial_id end link_consumers.any? do |consumer| consumer.intents.any? do |consumer_intent| can_be_consumed?(consumer, provider_intent, consumer_intent, @serial_id) end end end
ruby
def consumer?(provider_intent, deployment_plan) return true if provider_intent.shared link_consumers = deployment_plan.model.link_consumers link_consumers = link_consumers.select do |consumer| consumer.serial_id == @serial_id end link_consumers.any? do |consumer| consumer.intents.any? do |consumer_intent| can_be_consumed?(consumer, provider_intent, consumer_intent, @serial_id) end end end
[ "def", "consumer?", "(", "provider_intent", ",", "deployment_plan", ")", "return", "true", "if", "provider_intent", ".", "shared", "link_consumers", "=", "deployment_plan", ".", "model", ".", "link_consumers", "link_consumers", "=", "link_consumers", ".", "select", "do", "|", "consumer", "|", "consumer", ".", "serial_id", "==", "@serial_id", "end", "link_consumers", ".", "any?", "do", "|", "consumer", "|", "consumer", ".", "intents", ".", "any?", "do", "|", "consumer_intent", "|", "can_be_consumed?", "(", "consumer", ",", "provider_intent", ",", "consumer_intent", ",", "@serial_id", ")", "end", "end", "end" ]
A consumer which is within the same deployment
[ "A", "consumer", "which", "is", "within", "the", "same", "deployment" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/links/links_manager.rb#L466-L479
11,141
cloudfoundry/bosh
src/spec/support/wait.rb
Bosh::Spec.Waiter.wait
def wait(retries_left, &blk) blk.call rescue Exception => e retries_left -= 1 if retries_left > 0 sleep(0.5) retry else raise end end
ruby
def wait(retries_left, &blk) blk.call rescue Exception => e retries_left -= 1 if retries_left > 0 sleep(0.5) retry else raise end end
[ "def", "wait", "(", "retries_left", ",", "&", "blk", ")", "blk", ".", "call", "rescue", "Exception", "=>", "e", "retries_left", "-=", "1", "if", "retries_left", ">", "0", "sleep", "(", "0.5", ")", "retry", "else", "raise", "end", "end" ]
Do not add retries_left default value
[ "Do", "not", "add", "retries_left", "default", "value" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/spec/support/wait.rb#L8-L18
11,142
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/lock.rb
Bosh::Director.Lock.lock
def lock acquire @refresh_thread = Thread.new do renew_interval = [1.0, @expiration/2].max begin done_refreshing = false until @unlock || done_refreshing @refresh_mutex.synchronize do @refresh_signal.wait(@refresh_mutex, renew_interval) break if @unlock @logger.debug("Renewing lock: #@name") lock_expiration = Time.now.to_f + @expiration + 1 if Models::Lock.where(name: @name, uid: @uid).update(expired_at: Time.at(lock_expiration)) == 0 done_refreshing = true end end end ensure if !@unlock Models::Event.create( user: Config.current_job.username, action: 'lost', object_type: 'lock', object_name: @name, task: @task_id, deployment: @deployment_name, error: 'Lock renewal thread exiting', timestamp: Time.now, ) Models::Task[@task_id].update(state: 'cancelling') @logger.debug('Lock renewal thread exiting') end end end if block_given? begin yield ensure release end end end
ruby
def lock acquire @refresh_thread = Thread.new do renew_interval = [1.0, @expiration/2].max begin done_refreshing = false until @unlock || done_refreshing @refresh_mutex.synchronize do @refresh_signal.wait(@refresh_mutex, renew_interval) break if @unlock @logger.debug("Renewing lock: #@name") lock_expiration = Time.now.to_f + @expiration + 1 if Models::Lock.where(name: @name, uid: @uid).update(expired_at: Time.at(lock_expiration)) == 0 done_refreshing = true end end end ensure if !@unlock Models::Event.create( user: Config.current_job.username, action: 'lost', object_type: 'lock', object_name: @name, task: @task_id, deployment: @deployment_name, error: 'Lock renewal thread exiting', timestamp: Time.now, ) Models::Task[@task_id].update(state: 'cancelling') @logger.debug('Lock renewal thread exiting') end end end if block_given? begin yield ensure release end end end
[ "def", "lock", "acquire", "@refresh_thread", "=", "Thread", ".", "new", "do", "renew_interval", "=", "[", "1.0", ",", "@expiration", "/", "2", "]", ".", "max", "begin", "done_refreshing", "=", "false", "until", "@unlock", "||", "done_refreshing", "@refresh_mutex", ".", "synchronize", "do", "@refresh_signal", ".", "wait", "(", "@refresh_mutex", ",", "renew_interval", ")", "break", "if", "@unlock", "@logger", ".", "debug", "(", "\"Renewing lock: #@name\"", ")", "lock_expiration", "=", "Time", ".", "now", ".", "to_f", "+", "@expiration", "+", "1", "if", "Models", "::", "Lock", ".", "where", "(", "name", ":", "@name", ",", "uid", ":", "@uid", ")", ".", "update", "(", "expired_at", ":", "Time", ".", "at", "(", "lock_expiration", ")", ")", "==", "0", "done_refreshing", "=", "true", "end", "end", "end", "ensure", "if", "!", "@unlock", "Models", "::", "Event", ".", "create", "(", "user", ":", "Config", ".", "current_job", ".", "username", ",", "action", ":", "'lost'", ",", "object_type", ":", "'lock'", ",", "object_name", ":", "@name", ",", "task", ":", "@task_id", ",", "deployment", ":", "@deployment_name", ",", "error", ":", "'Lock renewal thread exiting'", ",", "timestamp", ":", "Time", ".", "now", ",", ")", "Models", "::", "Task", "[", "@task_id", "]", ".", "update", "(", "state", ":", "'cancelling'", ")", "@logger", ".", "debug", "(", "'Lock renewal thread exiting'", ")", "end", "end", "end", "if", "block_given?", "begin", "yield", "ensure", "release", "end", "end", "end" ]
Creates new lock with the given name. @param name lock name @option opts [Number] timeout how long to wait before giving up @option opts [Number] expiration how long to wait before expiring an old lock Acquire a lock. @yield [void] optional block to do work before automatically releasing the lock. @return [void]
[ "Creates", "new", "lock", "with", "the", "given", "name", "." ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/lock.rb#L36-L84
11,143
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/lock.rb
Bosh::Director.Lock.release
def release @refresh_mutex.synchronize { @unlock = true delete @refresh_signal.signal } @refresh_thread.join if @refresh_thread @event_manager.create_event( { user: Config.current_job.username, action: 'release', object_type: 'lock', object_name: @name, task: @task_id, deployment: @deployment_name, } ) end
ruby
def release @refresh_mutex.synchronize { @unlock = true delete @refresh_signal.signal } @refresh_thread.join if @refresh_thread @event_manager.create_event( { user: Config.current_job.username, action: 'release', object_type: 'lock', object_name: @name, task: @task_id, deployment: @deployment_name, } ) end
[ "def", "release", "@refresh_mutex", ".", "synchronize", "{", "@unlock", "=", "true", "delete", "@refresh_signal", ".", "signal", "}", "@refresh_thread", ".", "join", "if", "@refresh_thread", "@event_manager", ".", "create_event", "(", "{", "user", ":", "Config", ".", "current_job", ".", "username", ",", "action", ":", "'release'", ",", "object_type", ":", "'lock'", ",", "object_name", ":", "@name", ",", "task", ":", "@task_id", ",", "deployment", ":", "@deployment_name", ",", "}", ")", "end" ]
Release a lock that was not auto released by the lock method. @return [void]
[ "Release", "a", "lock", "that", "was", "not", "auto", "released", "by", "the", "lock", "method", "." ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/lock.rb#L89-L110
11,144
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/orphan_network_manager.rb
Bosh::Director.OrphanNetworkManager.list_orphan_networks
def list_orphan_networks Models::Network.where(orphaned: true).map do |network| { 'name' => network.name, 'type' => network.type, 'created_at' => network.created_at.to_s, 'orphaned_at' => network.orphaned_at.to_s, } end end
ruby
def list_orphan_networks Models::Network.where(orphaned: true).map do |network| { 'name' => network.name, 'type' => network.type, 'created_at' => network.created_at.to_s, 'orphaned_at' => network.orphaned_at.to_s, } end end
[ "def", "list_orphan_networks", "Models", "::", "Network", ".", "where", "(", "orphaned", ":", "true", ")", ".", "map", "do", "|", "network", "|", "{", "'name'", "=>", "network", ".", "name", ",", "'type'", "=>", "network", ".", "type", ",", "'created_at'", "=>", "network", ".", "created_at", ".", "to_s", ",", "'orphaned_at'", "=>", "network", ".", "orphaned_at", ".", "to_s", ",", "}", "end", "end" ]
returns a list of orphaned networks
[ "returns", "a", "list", "of", "orphaned", "networks" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/orphan_network_manager.rb#L38-L47
11,145
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/job_runner.rb
Bosh::Director.JobRunner.perform_job
def perform_job(*args) @task_logger.info('Creating job') job = @job_class.new(*args) Config.current_job = job job.task_id = @task_id job.task_checkpoint # cancelled in the queue? run_checkpointing @task_logger.info("Performing task: #{@task.inspect}") @task.timestamp = Time.now @task.started_at = Time.now @task.checkpoint_time = Time.now @task.save result = job.perform @task_logger.info('Done') finish_task(:done, result) rescue Bosh::Director::TaskCancelled => e log_exception(e) @task_logger.info("Task #{@task.id} cancelled") finish_task(:cancelled, 'task cancelled') rescue Exception => e log_exception(e) @task_logger.error("#{e}\n#{e.backtrace.join("\n")}") finish_task(:error, e) end
ruby
def perform_job(*args) @task_logger.info('Creating job') job = @job_class.new(*args) Config.current_job = job job.task_id = @task_id job.task_checkpoint # cancelled in the queue? run_checkpointing @task_logger.info("Performing task: #{@task.inspect}") @task.timestamp = Time.now @task.started_at = Time.now @task.checkpoint_time = Time.now @task.save result = job.perform @task_logger.info('Done') finish_task(:done, result) rescue Bosh::Director::TaskCancelled => e log_exception(e) @task_logger.info("Task #{@task.id} cancelled") finish_task(:cancelled, 'task cancelled') rescue Exception => e log_exception(e) @task_logger.error("#{e}\n#{e.backtrace.join("\n")}") finish_task(:error, e) end
[ "def", "perform_job", "(", "*", "args", ")", "@task_logger", ".", "info", "(", "'Creating job'", ")", "job", "=", "@job_class", ".", "new", "(", "args", ")", "Config", ".", "current_job", "=", "job", "job", ".", "task_id", "=", "@task_id", "job", ".", "task_checkpoint", "# cancelled in the queue?", "run_checkpointing", "@task_logger", ".", "info", "(", "\"Performing task: #{@task.inspect}\"", ")", "@task", ".", "timestamp", "=", "Time", ".", "now", "@task", ".", "started_at", "=", "Time", ".", "now", "@task", ".", "checkpoint_time", "=", "Time", ".", "now", "@task", ".", "save", "result", "=", "job", ".", "perform", "@task_logger", ".", "info", "(", "'Done'", ")", "finish_task", "(", ":done", ",", "result", ")", "rescue", "Bosh", "::", "Director", "::", "TaskCancelled", "=>", "e", "log_exception", "(", "e", ")", "@task_logger", ".", "info", "(", "\"Task #{@task.id} cancelled\"", ")", "finish_task", "(", ":cancelled", ",", "'task cancelled'", ")", "rescue", "Exception", "=>", "e", "log_exception", "(", "e", ")", "@task_logger", ".", "error", "(", "\"#{e}\\n#{e.backtrace.join(\"\\n\")}\"", ")", "finish_task", "(", ":error", ",", "e", ")", "end" ]
Instantiates and performs director job. @param [Array] args Opaque list of job arguments that will be used to instantiate the new job object. @return [void]
[ "Instantiates", "and", "performs", "director", "job", "." ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/job_runner.rb#L81-L112
11,146
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/job_runner.rb
Bosh::Director.JobRunner.run_checkpointing
def run_checkpointing # task check pointer is scoped to separate class to avoid # the secondary thread and main thread modifying the same @task # variable (and accidentally clobbering it in the process) task_checkpointer = TaskCheckPointer.new(@task.id) Thread.new do with_thread_name("task:#{@task.id}-checkpoint") do while true sleep(Config.task_checkpoint_interval) task_checkpointer.checkpoint end end end end
ruby
def run_checkpointing # task check pointer is scoped to separate class to avoid # the secondary thread and main thread modifying the same @task # variable (and accidentally clobbering it in the process) task_checkpointer = TaskCheckPointer.new(@task.id) Thread.new do with_thread_name("task:#{@task.id}-checkpoint") do while true sleep(Config.task_checkpoint_interval) task_checkpointer.checkpoint end end end end
[ "def", "run_checkpointing", "# task check pointer is scoped to separate class to avoid", "# the secondary thread and main thread modifying the same @task", "# variable (and accidentally clobbering it in the process)", "task_checkpointer", "=", "TaskCheckPointer", ".", "new", "(", "@task", ".", "id", ")", "Thread", ".", "new", "do", "with_thread_name", "(", "\"task:#{@task.id}-checkpoint\"", ")", "do", "while", "true", "sleep", "(", "Config", ".", "task_checkpoint_interval", ")", "task_checkpointer", ".", "checkpoint", "end", "end", "end", "end" ]
Spawns a thread that periodically updates task checkpoint time. There is no need to kill this thread as job execution lifetime is the same as worker process lifetime. @return [Thread] Checkpoint thread
[ "Spawns", "a", "thread", "that", "periodically", "updates", "task", "checkpoint", "time", ".", "There", "is", "no", "need", "to", "kill", "this", "thread", "as", "job", "execution", "lifetime", "is", "the", "same", "as", "worker", "process", "lifetime", "." ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/job_runner.rb#L118-L131
11,147
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/job_runner.rb
Bosh::Director.JobRunner.truncate
def truncate(string, len = 128) stripped = string.strip[0..len] if stripped.length > len stripped.gsub(/\s+?(\S+)?$/, "") + "..." else stripped end end
ruby
def truncate(string, len = 128) stripped = string.strip[0..len] if stripped.length > len stripped.gsub(/\s+?(\S+)?$/, "") + "..." else stripped end end
[ "def", "truncate", "(", "string", ",", "len", "=", "128", ")", "stripped", "=", "string", ".", "strip", "[", "0", "..", "len", "]", "if", "stripped", ".", "length", ">", "len", "stripped", ".", "gsub", "(", "/", "\\s", "\\S", "/", ",", "\"\"", ")", "+", "\"...\"", "else", "stripped", "end", "end" ]
Truncates string to fit task result length @param [String] string The original string @param [Integer] len Desired string length @return [String] Truncated string
[ "Truncates", "string", "to", "fit", "task", "result", "length" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/job_runner.rb#L137-L144
11,148
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/job_runner.rb
Bosh::Director.JobRunner.finish_task
def finish_task(state, result) @task.refresh @task.state = state @task.result = truncate(result.to_s) @task.timestamp = Time.now @task.save end
ruby
def finish_task(state, result) @task.refresh @task.state = state @task.result = truncate(result.to_s) @task.timestamp = Time.now @task.save end
[ "def", "finish_task", "(", "state", ",", "result", ")", "@task", ".", "refresh", "@task", ".", "state", "=", "state", "@task", ".", "result", "=", "truncate", "(", "result", ".", "to_s", ")", "@task", ".", "timestamp", "=", "Time", ".", "now", "@task", ".", "save", "end" ]
Marks task completion @param [Symbol] state Task completion state @param [#to_s] result
[ "Marks", "task", "completion" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/job_runner.rb#L149-L155
11,149
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/job_runner.rb
Bosh::Director.JobRunner.log_exception
def log_exception(exception) # Event log is being used here to propagate the error. # It's up to event log renderer to find the error and # signal it properly. director_error = DirectorError.create_from_exception(exception) Config.event_log.log_error(director_error) end
ruby
def log_exception(exception) # Event log is being used here to propagate the error. # It's up to event log renderer to find the error and # signal it properly. director_error = DirectorError.create_from_exception(exception) Config.event_log.log_error(director_error) end
[ "def", "log_exception", "(", "exception", ")", "# Event log is being used here to propagate the error.", "# It's up to event log renderer to find the error and", "# signal it properly.", "director_error", "=", "DirectorError", ".", "create_from_exception", "(", "exception", ")", "Config", ".", "event_log", ".", "log_error", "(", "director_error", ")", "end" ]
Logs the exception in the event log @param [Exception] exception
[ "Logs", "the", "exception", "in", "the", "event", "log" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/job_runner.rb#L159-L165
11,150
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/compiled_package_requirement_generator.rb
Bosh::Director.CompiledPackageRequirementGenerator.generate!
def generate!(requirements, instance_group, job, package, stemcell) # Our assumption here is that package dependency graph # has no cycles: this is being enforced on release upload. # Other than that it's a vanilla Depth-First Search (DFS). @logger.info("Checking whether package '#{package.desc}' needs to be compiled for stemcell '#{stemcell.desc}'") requirement_key = [package.id, "#{stemcell.os}/#{stemcell.version}"] requirement = requirements[requirement_key] if requirement # We already visited this and its dependencies requirement.add_instance_group(instance_group) # But we still need to register with this instance group return requirement end package_dependency_manager = PackageDependenciesManager.new(job.release.model) requirement = create_requirement(instance_group, job, package, stemcell, package_dependency_manager) @logger.info("Processing package '#{package.desc}' dependencies") dependencies = package_dependency_manager.dependencies(package) dependencies.each do |dependency| @logger.info("Package '#{package.desc}' depends on package '#{dependency.desc}'") dependency_requirement = generate!(requirements, instance_group, job, dependency, stemcell) requirement.add_dependency(dependency_requirement) end requirements[requirement_key] = requirement requirement end
ruby
def generate!(requirements, instance_group, job, package, stemcell) # Our assumption here is that package dependency graph # has no cycles: this is being enforced on release upload. # Other than that it's a vanilla Depth-First Search (DFS). @logger.info("Checking whether package '#{package.desc}' needs to be compiled for stemcell '#{stemcell.desc}'") requirement_key = [package.id, "#{stemcell.os}/#{stemcell.version}"] requirement = requirements[requirement_key] if requirement # We already visited this and its dependencies requirement.add_instance_group(instance_group) # But we still need to register with this instance group return requirement end package_dependency_manager = PackageDependenciesManager.new(job.release.model) requirement = create_requirement(instance_group, job, package, stemcell, package_dependency_manager) @logger.info("Processing package '#{package.desc}' dependencies") dependencies = package_dependency_manager.dependencies(package) dependencies.each do |dependency| @logger.info("Package '#{package.desc}' depends on package '#{dependency.desc}'") dependency_requirement = generate!(requirements, instance_group, job, dependency, stemcell) requirement.add_dependency(dependency_requirement) end requirements[requirement_key] = requirement requirement end
[ "def", "generate!", "(", "requirements", ",", "instance_group", ",", "job", ",", "package", ",", "stemcell", ")", "# Our assumption here is that package dependency graph", "# has no cycles: this is being enforced on release upload.", "# Other than that it's a vanilla Depth-First Search (DFS).", "@logger", ".", "info", "(", "\"Checking whether package '#{package.desc}' needs to be compiled for stemcell '#{stemcell.desc}'\"", ")", "requirement_key", "=", "[", "package", ".", "id", ",", "\"#{stemcell.os}/#{stemcell.version}\"", "]", "requirement", "=", "requirements", "[", "requirement_key", "]", "if", "requirement", "# We already visited this and its dependencies", "requirement", ".", "add_instance_group", "(", "instance_group", ")", "# But we still need to register with this instance group", "return", "requirement", "end", "package_dependency_manager", "=", "PackageDependenciesManager", ".", "new", "(", "job", ".", "release", ".", "model", ")", "requirement", "=", "create_requirement", "(", "instance_group", ",", "job", ",", "package", ",", "stemcell", ",", "package_dependency_manager", ")", "@logger", ".", "info", "(", "\"Processing package '#{package.desc}' dependencies\"", ")", "dependencies", "=", "package_dependency_manager", ".", "dependencies", "(", "package", ")", "dependencies", ".", "each", "do", "|", "dependency", "|", "@logger", ".", "info", "(", "\"Package '#{package.desc}' depends on package '#{dependency.desc}'\"", ")", "dependency_requirement", "=", "generate!", "(", "requirements", ",", "instance_group", ",", "job", ",", "dependency", ",", "stemcell", ")", "requirement", ".", "add_dependency", "(", "dependency_requirement", ")", "end", "requirements", "[", "requirement_key", "]", "=", "requirement", "requirement", "end" ]
The rquirements hash passed in by the caller will be populated with CompiledPackageRequirement objects
[ "The", "rquirements", "hash", "passed", "in", "by", "the", "caller", "will", "be", "populated", "with", "CompiledPackageRequirement", "objects" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/compiled_package_requirement_generator.rb#L12-L40
11,151
cloudfoundry/bosh
src/bosh-director/lib/bosh/director/deployment_plan/assembler.rb
Bosh::Director.DeploymentPlan::Assembler.bind_jobs
def bind_jobs @deployment_plan.releases.each do |release| release.bind_jobs end @deployment_plan.instance_groups.each(&:validate_package_names_do_not_collide!) @deployment_plan.instance_groups.each(&:validate_exported_from_matches_stemcell!) end
ruby
def bind_jobs @deployment_plan.releases.each do |release| release.bind_jobs end @deployment_plan.instance_groups.each(&:validate_package_names_do_not_collide!) @deployment_plan.instance_groups.each(&:validate_exported_from_matches_stemcell!) end
[ "def", "bind_jobs", "@deployment_plan", ".", "releases", ".", "each", "do", "|", "release", "|", "release", ".", "bind_jobs", "end", "@deployment_plan", ".", "instance_groups", ".", "each", "(", ":validate_package_names_do_not_collide!", ")", "@deployment_plan", ".", "instance_groups", ".", "each", "(", ":validate_exported_from_matches_stemcell!", ")", "end" ]
Binds template models for each release spec in the deployment plan @return [void]
[ "Binds", "template", "models", "for", "each", "release", "spec", "in", "the", "deployment", "plan" ]
2eaa7100879ddd20cd909cd698514746195e28b7
https://github.com/cloudfoundry/bosh/blob/2eaa7100879ddd20cd909cd698514746195e28b7/src/bosh-director/lib/bosh/director/deployment_plan/assembler.rb#L190-L197
11,152
GeorgeKaraszi/ActiveRecordExtended
lib/active_record_extended/utilities.rb
ActiveRecordExtended.Utilities.double_quote
def double_quote(value) return if value.nil? case value.to_s # Ignore keys that contain double quotes or a Arel.star (*)[all columns] # or if a table has already been explicitly declared (ex: users.id) when "*", /((^".+"$)|(^[[:alpha:]]+\.[[:alnum:]]+))/ value else PG::Connection.quote_ident(value.to_s) end end
ruby
def double_quote(value) return if value.nil? case value.to_s # Ignore keys that contain double quotes or a Arel.star (*)[all columns] # or if a table has already been explicitly declared (ex: users.id) when "*", /((^".+"$)|(^[[:alpha:]]+\.[[:alnum:]]+))/ value else PG::Connection.quote_ident(value.to_s) end end
[ "def", "double_quote", "(", "value", ")", "return", "if", "value", ".", "nil?", "case", "value", ".", "to_s", "# Ignore keys that contain double quotes or a Arel.star (*)[all columns]", "# or if a table has already been explicitly declared (ex: users.id)", "when", "\"*\"", ",", "/", "\\.", "/", "value", "else", "PG", "::", "Connection", ".", "quote_ident", "(", "value", ".", "to_s", ")", "end", "end" ]
Ensures the given value is properly double quoted. This also ensures we don't have conflicts with reversed keywords. IE: `user` is a reserved keyword in PG. But `"user"` is allowed and works the same when used as an column/tbl alias.
[ "Ensures", "the", "given", "value", "is", "properly", "double", "quoted", ".", "This", "also", "ensures", "we", "don", "t", "have", "conflicts", "with", "reversed", "keywords", "." ]
aca74eebb64b9957a2c8765bef6e43c7d5736fd8
https://github.com/GeorgeKaraszi/ActiveRecordExtended/blob/aca74eebb64b9957a2c8765bef6e43c7d5736fd8/lib/active_record_extended/utilities.rb#L108-L119
11,153
GeorgeKaraszi/ActiveRecordExtended
lib/active_record_extended/utilities.rb
ActiveRecordExtended.Utilities.literal_key
def literal_key(key) case key when TrueClass then "'t'" when FalseClass then "'f'" when Numeric then key else key = key.to_s key.start_with?("'") && key.end_with?("'") ? key : "'#{key}'" end end
ruby
def literal_key(key) case key when TrueClass then "'t'" when FalseClass then "'f'" when Numeric then key else key = key.to_s key.start_with?("'") && key.end_with?("'") ? key : "'#{key}'" end end
[ "def", "literal_key", "(", "key", ")", "case", "key", "when", "TrueClass", "then", "\"'t'\"", "when", "FalseClass", "then", "\"'f'\"", "when", "Numeric", "then", "key", "else", "key", "=", "key", ".", "to_s", "key", ".", "start_with?", "(", "\"'\"", ")", "&&", "key", ".", "end_with?", "(", "\"'\"", ")", "?", "key", ":", "\"'#{key}'\"", "end", "end" ]
Ensures the key is properly single quoted and treated as a actual PG key reference.
[ "Ensures", "the", "key", "is", "properly", "single", "quoted", "and", "treated", "as", "a", "actual", "PG", "key", "reference", "." ]
aca74eebb64b9957a2c8765bef6e43c7d5736fd8
https://github.com/GeorgeKaraszi/ActiveRecordExtended/blob/aca74eebb64b9957a2c8765bef6e43c7d5736fd8/lib/active_record_extended/utilities.rb#L122-L131
11,154
GeorgeKaraszi/ActiveRecordExtended
lib/active_record_extended/utilities.rb
ActiveRecordExtended.Utilities.to_arel_sql
def to_arel_sql(value) case value when Arel::Node, Arel::Nodes::SqlLiteral, nil value when ActiveRecord::Relation Arel.sql(value.spawn.to_sql) else Arel.sql(value.respond_to?(:to_sql) ? value.to_sql : value.to_s) end end
ruby
def to_arel_sql(value) case value when Arel::Node, Arel::Nodes::SqlLiteral, nil value when ActiveRecord::Relation Arel.sql(value.spawn.to_sql) else Arel.sql(value.respond_to?(:to_sql) ? value.to_sql : value.to_s) end end
[ "def", "to_arel_sql", "(", "value", ")", "case", "value", "when", "Arel", "::", "Node", ",", "Arel", "::", "Nodes", "::", "SqlLiteral", ",", "nil", "value", "when", "ActiveRecord", "::", "Relation", "Arel", ".", "sql", "(", "value", ".", "spawn", ".", "to_sql", ")", "else", "Arel", ".", "sql", "(", "value", ".", "respond_to?", "(", ":to_sql", ")", "?", "value", ".", "to_sql", ":", "value", ".", "to_s", ")", "end", "end" ]
Converts a potential subquery into a compatible Arel SQL node. Note: We convert relations to SQL to maintain compatibility with Rails 5.[0/1]. Only Rails 5.2+ maintains bound attributes in Arel, so its better to be safe then sorry. When we drop support for Rails 5.[0/1], we then can then drop the '.to_sql' conversation
[ "Converts", "a", "potential", "subquery", "into", "a", "compatible", "Arel", "SQL", "node", "." ]
aca74eebb64b9957a2c8765bef6e43c7d5736fd8
https://github.com/GeorgeKaraszi/ActiveRecordExtended/blob/aca74eebb64b9957a2c8765bef6e43c7d5736fd8/lib/active_record_extended/utilities.rb#L140-L149
11,155
GeorgeKaraszi/ActiveRecordExtended
lib/active_record_extended/query_methods/where_chain.rb
ActiveRecordExtended.WhereChain.contains
def contains(opts, *rest) build_where_chain(opts, rest) do |arel| case arel when Arel::Nodes::In, Arel::Nodes::Equality column = left_column(arel) || column_from_association(arel) if [:hstore, :jsonb].include?(column.type) Arel::Nodes::ContainsHStore.new(arel.left, arel.right) elsif column.try(:array) Arel::Nodes::ContainsArray.new(arel.left, arel.right) else raise ArgumentError, "Invalid argument for .where.contains(), got #{arel.class}" end else raise ArgumentError, "Invalid argument for .where.contains(), got #{arel.class}" end end end
ruby
def contains(opts, *rest) build_where_chain(opts, rest) do |arel| case arel when Arel::Nodes::In, Arel::Nodes::Equality column = left_column(arel) || column_from_association(arel) if [:hstore, :jsonb].include?(column.type) Arel::Nodes::ContainsHStore.new(arel.left, arel.right) elsif column.try(:array) Arel::Nodes::ContainsArray.new(arel.left, arel.right) else raise ArgumentError, "Invalid argument for .where.contains(), got #{arel.class}" end else raise ArgumentError, "Invalid argument for .where.contains(), got #{arel.class}" end end end
[ "def", "contains", "(", "opts", ",", "*", "rest", ")", "build_where_chain", "(", "opts", ",", "rest", ")", "do", "|", "arel", "|", "case", "arel", "when", "Arel", "::", "Nodes", "::", "In", ",", "Arel", "::", "Nodes", "::", "Equality", "column", "=", "left_column", "(", "arel", ")", "||", "column_from_association", "(", "arel", ")", "if", "[", ":hstore", ",", ":jsonb", "]", ".", "include?", "(", "column", ".", "type", ")", "Arel", "::", "Nodes", "::", "ContainsHStore", ".", "new", "(", "arel", ".", "left", ",", "arel", ".", "right", ")", "elsif", "column", ".", "try", "(", ":array", ")", "Arel", "::", "Nodes", "::", "ContainsArray", ".", "new", "(", "arel", ".", "left", ",", "arel", ".", "right", ")", "else", "raise", "ArgumentError", ",", "\"Invalid argument for .where.contains(), got #{arel.class}\"", "end", "else", "raise", "ArgumentError", ",", "\"Invalid argument for .where.contains(), got #{arel.class}\"", "end", "end", "end" ]
Finds Records that contains a nested set elements Array Column Type: User.where.contains(tags: [1, 3]) # SELECT user.* FROM user WHERE user.tags @> {1,3} HStore Column Type: User.where.contains(data: { nickname: 'chainer' }) # SELECT user.* FROM user WHERE user.data @> 'nickname' => 'chainer' JSONB Column Type: User.where.contains(data: { nickname: 'chainer' }) # SELECT user.* FROM user WHERE user.data @> {'nickname': 'chainer'} This can also be used along side joined tables JSONB Column Type Example: Tag.joins(:user).where.contains(user: { data: { nickname: 'chainer' } }) # SELECT tags.* FROM tags INNER JOIN user on user.id = tags.user_id WHERE user.data @> { nickname: 'chainer' }
[ "Finds", "Records", "that", "contains", "a", "nested", "set", "elements" ]
aca74eebb64b9957a2c8765bef6e43c7d5736fd8
https://github.com/GeorgeKaraszi/ActiveRecordExtended/blob/aca74eebb64b9957a2c8765bef6e43c7d5736fd8/lib/active_record_extended/query_methods/where_chain.rb#L46-L63
11,156
jekyll/jekyll-admin
lib/jekyll-admin/urlable.rb
JekyllAdmin.URLable.api_url
def api_url @api_url ||= Addressable::URI.new( :scheme => scheme, :host => host, :port => port, :path => path_with_base("/_api", resource_path) ).normalize.to_s end
ruby
def api_url @api_url ||= Addressable::URI.new( :scheme => scheme, :host => host, :port => port, :path => path_with_base("/_api", resource_path) ).normalize.to_s end
[ "def", "api_url", "@api_url", "||=", "Addressable", "::", "URI", ".", "new", "(", ":scheme", "=>", "scheme", ",", ":host", "=>", "host", ",", ":port", "=>", "port", ",", ":path", "=>", "path_with_base", "(", "\"/_api\"", ",", "resource_path", ")", ")", ".", "normalize", ".", "to_s", "end" ]
Absolute URL to the API representation of this resource
[ "Absolute", "URL", "to", "the", "API", "representation", "of", "this", "resource" ]
bc053b3b93faba679e8666091c42c47970e3bb5e
https://github.com/jekyll/jekyll-admin/blob/bc053b3b93faba679e8666091c42c47970e3bb5e/lib/jekyll-admin/urlable.rb#L17-L22
11,157
jekyll/jekyll-admin
lib/jekyll-admin/apiable.rb
JekyllAdmin.APIable.to_api
def to_api(include_content: false) output = hash_for_api output = output.merge(url_fields) # Include content, if requested, otherwise remove it if include_content output = output.merge(content_fields) else CONTENT_FIELDS.each { |field| output.delete(field) } end # Documents have duplicate output and content fields, Pages do not # Since it's an API, use `content` in both for consistency output.delete("output") # By default, calling to_liquid on a collection will return a docs # array with each rendered document, which we don't want. if is_a?(Jekyll::Collection) output.delete("docs") output["entries_url"] = entries_url end if is_a?(Jekyll::Document) output["relative_path"] = relative_path.sub("_drafts/", "") if draft? output["name"] = basename end if is_a?(Jekyll::StaticFile) output["from_theme"] = from_theme_gem? end output end
ruby
def to_api(include_content: false) output = hash_for_api output = output.merge(url_fields) # Include content, if requested, otherwise remove it if include_content output = output.merge(content_fields) else CONTENT_FIELDS.each { |field| output.delete(field) } end # Documents have duplicate output and content fields, Pages do not # Since it's an API, use `content` in both for consistency output.delete("output") # By default, calling to_liquid on a collection will return a docs # array with each rendered document, which we don't want. if is_a?(Jekyll::Collection) output.delete("docs") output["entries_url"] = entries_url end if is_a?(Jekyll::Document) output["relative_path"] = relative_path.sub("_drafts/", "") if draft? output["name"] = basename end if is_a?(Jekyll::StaticFile) output["from_theme"] = from_theme_gem? end output end
[ "def", "to_api", "(", "include_content", ":", "false", ")", "output", "=", "hash_for_api", "output", "=", "output", ".", "merge", "(", "url_fields", ")", "# Include content, if requested, otherwise remove it", "if", "include_content", "output", "=", "output", ".", "merge", "(", "content_fields", ")", "else", "CONTENT_FIELDS", ".", "each", "{", "|", "field", "|", "output", ".", "delete", "(", "field", ")", "}", "end", "# Documents have duplicate output and content fields, Pages do not", "# Since it's an API, use `content` in both for consistency", "output", ".", "delete", "(", "\"output\"", ")", "# By default, calling to_liquid on a collection will return a docs", "# array with each rendered document, which we don't want.", "if", "is_a?", "(", "Jekyll", "::", "Collection", ")", "output", ".", "delete", "(", "\"docs\"", ")", "output", "[", "\"entries_url\"", "]", "=", "entries_url", "end", "if", "is_a?", "(", "Jekyll", "::", "Document", ")", "output", "[", "\"relative_path\"", "]", "=", "relative_path", ".", "sub", "(", "\"_drafts/\"", ",", "\"\"", ")", "if", "draft?", "output", "[", "\"name\"", "]", "=", "basename", "end", "if", "is_a?", "(", "Jekyll", "::", "StaticFile", ")", "output", "[", "\"from_theme\"", "]", "=", "from_theme_gem?", "end", "output", "end" ]
Returns a hash suitable for use as an API response. For Documents and Pages: 1. Adds the file's raw content to the `raw_content` field 2. Adds the file's raw YAML front matter to the `front_matter` field For Static Files it addes the Base64 `encoded_content` field Options: include_content - if true, includes the content in the respond, false by default to support mapping on indexes where we only want metadata Returns a hash (which can then be to_json'd)
[ "Returns", "a", "hash", "suitable", "for", "use", "as", "an", "API", "response", "." ]
bc053b3b93faba679e8666091c42c47970e3bb5e
https://github.com/jekyll/jekyll-admin/blob/bc053b3b93faba679e8666091c42c47970e3bb5e/lib/jekyll-admin/apiable.rb#L24-L56
11,158
jekyll/jekyll-admin
lib/jekyll-admin/apiable.rb
JekyllAdmin.APIable.content_fields
def content_fields output = {} # Include file content-related fields if is_a?(Jekyll::StaticFile) output["encoded_content"] = encoded_content elsif is_a?(JekyllAdmin::DataFile) output["content"] = content output["raw_content"] = raw_content else output["raw_content"] = raw_content output["front_matter"] = front_matter end # Include next and previous documents non-recursively if is_a?(Jekyll::Document) %w(next previous).each do |direction| method = "#{direction}_doc".to_sym doc = public_send(method) output[direction] = doc.to_api if doc end end output end
ruby
def content_fields output = {} # Include file content-related fields if is_a?(Jekyll::StaticFile) output["encoded_content"] = encoded_content elsif is_a?(JekyllAdmin::DataFile) output["content"] = content output["raw_content"] = raw_content else output["raw_content"] = raw_content output["front_matter"] = front_matter end # Include next and previous documents non-recursively if is_a?(Jekyll::Document) %w(next previous).each do |direction| method = "#{direction}_doc".to_sym doc = public_send(method) output[direction] = doc.to_api if doc end end output end
[ "def", "content_fields", "output", "=", "{", "}", "# Include file content-related fields", "if", "is_a?", "(", "Jekyll", "::", "StaticFile", ")", "output", "[", "\"encoded_content\"", "]", "=", "encoded_content", "elsif", "is_a?", "(", "JekyllAdmin", "::", "DataFile", ")", "output", "[", "\"content\"", "]", "=", "content", "output", "[", "\"raw_content\"", "]", "=", "raw_content", "else", "output", "[", "\"raw_content\"", "]", "=", "raw_content", "output", "[", "\"front_matter\"", "]", "=", "front_matter", "end", "# Include next and previous documents non-recursively", "if", "is_a?", "(", "Jekyll", "::", "Document", ")", "%w(", "next", "previous", ")", ".", "each", "do", "|", "direction", "|", "method", "=", "\"#{direction}_doc\"", ".", "to_sym", "doc", "=", "public_send", "(", "method", ")", "output", "[", "direction", "]", "=", "doc", ".", "to_api", "if", "doc", "end", "end", "output", "end" ]
Returns a hash of content fields for inclusion in the API output
[ "Returns", "a", "hash", "of", "content", "fields", "for", "inclusion", "in", "the", "API", "output" ]
bc053b3b93faba679e8666091c42c47970e3bb5e
https://github.com/jekyll/jekyll-admin/blob/bc053b3b93faba679e8666091c42c47970e3bb5e/lib/jekyll-admin/apiable.rb#L128-L152
11,159
jekyll/jekyll-admin
lib/jekyll-admin/path_helper.rb
JekyllAdmin.PathHelper.directory_path
def directory_path sanitized_path( case namespace when "collections" File.join(collection.relative_directory, params["splat"].first) when "data" File.join(DataFile.data_dir, params["splat"].first) when "drafts" File.join("_drafts", params["splat"].first) else params["splat"].first end ) end
ruby
def directory_path sanitized_path( case namespace when "collections" File.join(collection.relative_directory, params["splat"].first) when "data" File.join(DataFile.data_dir, params["splat"].first) when "drafts" File.join("_drafts", params["splat"].first) else params["splat"].first end ) end
[ "def", "directory_path", "sanitized_path", "(", "case", "namespace", "when", "\"collections\"", "File", ".", "join", "(", "collection", ".", "relative_directory", ",", "params", "[", "\"splat\"", "]", ".", "first", ")", "when", "\"data\"", "File", ".", "join", "(", "DataFile", ".", "data_dir", ",", "params", "[", "\"splat\"", "]", ".", "first", ")", "when", "\"drafts\"", "File", ".", "join", "(", "\"_drafts\"", ",", "params", "[", "\"splat\"", "]", ".", "first", ")", "else", "params", "[", "\"splat\"", "]", ".", "first", "end", ")", "end" ]
Returns the path to the requested file's containing directory
[ "Returns", "the", "path", "to", "the", "requested", "file", "s", "containing", "directory" ]
bc053b3b93faba679e8666091c42c47970e3bb5e
https://github.com/jekyll/jekyll-admin/blob/bc053b3b93faba679e8666091c42c47970e3bb5e/lib/jekyll-admin/path_helper.rb#L54-L67
11,160
jekyll/jekyll-admin
lib/jekyll-admin/file_helper.rb
JekyllAdmin.FileHelper.write_file
def write_file(path, content) Jekyll.logger.debug "WRITING:", path path = sanitized_path(path) FileUtils.mkdir_p File.dirname(path) File.open(path, "wb") do |file| file.write(content) end # we should fully process in dev mode for tests to pass if ENV["RACK_ENV"] == "production" site.read else site.process end end
ruby
def write_file(path, content) Jekyll.logger.debug "WRITING:", path path = sanitized_path(path) FileUtils.mkdir_p File.dirname(path) File.open(path, "wb") do |file| file.write(content) end # we should fully process in dev mode for tests to pass if ENV["RACK_ENV"] == "production" site.read else site.process end end
[ "def", "write_file", "(", "path", ",", "content", ")", "Jekyll", ".", "logger", ".", "debug", "\"WRITING:\"", ",", "path", "path", "=", "sanitized_path", "(", "path", ")", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "path", ")", "File", ".", "open", "(", "path", ",", "\"wb\"", ")", "do", "|", "file", "|", "file", ".", "write", "(", "content", ")", "end", "# we should fully process in dev mode for tests to pass", "if", "ENV", "[", "\"RACK_ENV\"", "]", "==", "\"production\"", "site", ".", "read", "else", "site", ".", "process", "end", "end" ]
Write a file to disk with the given content
[ "Write", "a", "file", "to", "disk", "with", "the", "given", "content" ]
bc053b3b93faba679e8666091c42c47970e3bb5e
https://github.com/jekyll/jekyll-admin/blob/bc053b3b93faba679e8666091c42c47970e3bb5e/lib/jekyll-admin/file_helper.rb#L17-L30
11,161
jekyll/jekyll-admin
lib/jekyll-admin/file_helper.rb
JekyllAdmin.FileHelper.delete_file
def delete_file(path) Jekyll.logger.debug "DELETING:", path FileUtils.rm_f sanitized_path(path) site.process end
ruby
def delete_file(path) Jekyll.logger.debug "DELETING:", path FileUtils.rm_f sanitized_path(path) site.process end
[ "def", "delete_file", "(", "path", ")", "Jekyll", ".", "logger", ".", "debug", "\"DELETING:\"", ",", "path", "FileUtils", ".", "rm_f", "sanitized_path", "(", "path", ")", "site", ".", "process", "end" ]
Delete the file at the given path
[ "Delete", "the", "file", "at", "the", "given", "path" ]
bc053b3b93faba679e8666091c42c47970e3bb5e
https://github.com/jekyll/jekyll-admin/blob/bc053b3b93faba679e8666091c42c47970e3bb5e/lib/jekyll-admin/file_helper.rb#L33-L37
11,162
jekyll/jekyll-admin
lib/jekyll-admin/server.rb
JekyllAdmin.Server.restored_front_matter
def restored_front_matter front_matter.map do |key, value| value = "null" if value.nil? [key, value] end.to_h end
ruby
def restored_front_matter front_matter.map do |key, value| value = "null" if value.nil? [key, value] end.to_h end
[ "def", "restored_front_matter", "front_matter", ".", "map", "do", "|", "key", ",", "value", "|", "value", "=", "\"null\"", "if", "value", ".", "nil?", "[", "key", ",", "value", "]", "end", ".", "to_h", "end" ]
verbose 'null' values in front matter
[ "verbose", "null", "values", "in", "front", "matter" ]
bc053b3b93faba679e8666091c42c47970e3bb5e
https://github.com/jekyll/jekyll-admin/blob/bc053b3b93faba679e8666091c42c47970e3bb5e/lib/jekyll-admin/server.rb#L87-L92
11,163
sds/scss-lint
lib/scss_lint/linter/single_line_per_property.rb
SCSSLint.Linter::SingleLinePerProperty.single_line_rule_set?
def single_line_rule_set?(rule) rule.children.all? { |child| child.line == rule.source_range.end_pos.line } end
ruby
def single_line_rule_set?(rule) rule.children.all? { |child| child.line == rule.source_range.end_pos.line } end
[ "def", "single_line_rule_set?", "(", "rule", ")", "rule", ".", "children", ".", "all?", "{", "|", "child", "|", "child", ".", "line", "==", "rule", ".", "source_range", ".", "end_pos", ".", "line", "}", "end" ]
Return whether this rule set occupies a single line. Note that this allows: a, b, i { margin: 0; padding: 0; } and: p { margin: 0; padding: 0; } In other words, the line of the opening curly brace is the line that the rule set is considered to occupy.
[ "Return", "whether", "this", "rule", "set", "occupies", "a", "single", "line", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/single_line_per_property.rb#L41-L43
11,164
sds/scss-lint
lib/scss_lint/linter/single_line_per_property.rb
SCSSLint.Linter::SingleLinePerProperty.check_adjacent_properties
def check_adjacent_properties(properties) properties[0..-2].zip(properties[1..-1]).each do |first, second| next unless first.line == second.line add_lint(second, "Property '#{second.name.join}' should be placed on own line") end end
ruby
def check_adjacent_properties(properties) properties[0..-2].zip(properties[1..-1]).each do |first, second| next unless first.line == second.line add_lint(second, "Property '#{second.name.join}' should be placed on own line") end end
[ "def", "check_adjacent_properties", "(", "properties", ")", "properties", "[", "0", "..", "-", "2", "]", ".", "zip", "(", "properties", "[", "1", "..", "-", "1", "]", ")", ".", "each", "do", "|", "first", ",", "second", "|", "next", "unless", "first", ".", "line", "==", "second", ".", "line", "add_lint", "(", "second", ",", "\"Property '#{second.name.join}' should be placed on own line\"", ")", "end", "end" ]
Compare each property against the next property to see if they are on the same line. @param properties [Array<Sass::Tree::PropNode>]
[ "Compare", "each", "property", "against", "the", "next", "property", "to", "see", "if", "they", "are", "on", "the", "same", "line", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/single_line_per_property.rb#L53-L59
11,165
sds/scss-lint
lib/scss_lint/control_comment_processor.rb
SCSSLint.ControlCommentProcessor.before_node_visit
def before_node_visit(node) return unless (commands = Array(extract_commands(node))).any? commands.each do |command| linters = command[:linters] next unless linters.include?('all') || linters.include?(@linter.name) process_command(command, node) # Is the control comment the only thing on this line? next if node.is_a?(Sass::Tree::RuleNode) || %r{^\s*(//|/\*)}.match(@linter.engine.lines[command[:line] - 1]) # Otherwise, pop since we only want comment to apply to the single line pop_control_comment_stack(node) end end
ruby
def before_node_visit(node) return unless (commands = Array(extract_commands(node))).any? commands.each do |command| linters = command[:linters] next unless linters.include?('all') || linters.include?(@linter.name) process_command(command, node) # Is the control comment the only thing on this line? next if node.is_a?(Sass::Tree::RuleNode) || %r{^\s*(//|/\*)}.match(@linter.engine.lines[command[:line] - 1]) # Otherwise, pop since we only want comment to apply to the single line pop_control_comment_stack(node) end end
[ "def", "before_node_visit", "(", "node", ")", "return", "unless", "(", "commands", "=", "Array", "(", "extract_commands", "(", "node", ")", ")", ")", ".", "any?", "commands", ".", "each", "do", "|", "command", "|", "linters", "=", "command", "[", ":linters", "]", "next", "unless", "linters", ".", "include?", "(", "'all'", ")", "||", "linters", ".", "include?", "(", "@linter", ".", "name", ")", "process_command", "(", "command", ",", "node", ")", "# Is the control comment the only thing on this line?", "next", "if", "node", ".", "is_a?", "(", "Sass", "::", "Tree", "::", "RuleNode", ")", "||", "%r{", "\\s", "\\*", "}", ".", "match", "(", "@linter", ".", "engine", ".", "lines", "[", "command", "[", ":line", "]", "-", "1", "]", ")", "# Otherwise, pop since we only want comment to apply to the single line", "pop_control_comment_stack", "(", "node", ")", "end", "end" ]
Executed before a node has been visited. @param node [Sass::Tree::Node]
[ "Executed", "before", "a", "node", "has", "been", "visited", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/control_comment_processor.rb#L22-L38
11,166
sds/scss-lint
lib/scss_lint/control_comment_processor.rb
SCSSLint.ControlCommentProcessor.last_child
def last_child(node) last = node.children.inject(node) do |lowest, child| return lowest unless child.respond_to?(:line) lowest.line < child.line ? child : lowest end # In this case, none of the children have associated line numbers or the # node has no children at all, so return `nil`. return if last == node last end
ruby
def last_child(node) last = node.children.inject(node) do |lowest, child| return lowest unless child.respond_to?(:line) lowest.line < child.line ? child : lowest end # In this case, none of the children have associated line numbers or the # node has no children at all, so return `nil`. return if last == node last end
[ "def", "last_child", "(", "node", ")", "last", "=", "node", ".", "children", ".", "inject", "(", "node", ")", "do", "|", "lowest", ",", "child", "|", "return", "lowest", "unless", "child", ".", "respond_to?", "(", ":line", ")", "lowest", ".", "line", "<", "child", ".", "line", "?", "child", ":", "lowest", "end", "# In this case, none of the children have associated line numbers or the", "# node has no children at all, so return `nil`.", "return", "if", "last", "==", "node", "last", "end" ]
Gets the child of the node that resides on the lowest line in the file. This is necessary due to the fact that our monkey patching of the parse tree's {#children} method does not return nodes sorted by their line number. Returns `nil` if node has no children or no children with associated line numbers. @param node [Sass::Tree::Node, Sass::Script::Tree::Node] @return [Sass::Tree::Node, Sass::Script::Tree::Node]
[ "Gets", "the", "child", "of", "the", "node", "that", "resides", "on", "the", "lowest", "line", "in", "the", "file", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/control_comment_processor.rb#L137-L148
11,167
sds/scss-lint
lib/scss_lint/linter/qualifying_element.rb
SCSSLint.Linter::QualifyingElement.seq_contains_sel_class?
def seq_contains_sel_class?(seq, selector_class) seq.members.any? do |simple| simple.is_a?(selector_class) end end
ruby
def seq_contains_sel_class?(seq, selector_class) seq.members.any? do |simple| simple.is_a?(selector_class) end end
[ "def", "seq_contains_sel_class?", "(", "seq", ",", "selector_class", ")", "seq", ".", "members", ".", "any?", "do", "|", "simple", "|", "simple", ".", "is_a?", "(", "selector_class", ")", "end", "end" ]
Checks if a simple sequence contains a simple selector of a certain class. @param seq [Sass::Selector::SimpleSequence] @param selector_class [Sass::Selector::Simple] @returns [Boolean]
[ "Checks", "if", "a", "simple", "sequence", "contains", "a", "simple", "selector", "of", "a", "certain", "class", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/qualifying_element.rb#L21-L25
11,168
sds/scss-lint
lib/scss_lint/linter/selector_depth.rb
SCSSLint.Linter::SelectorDepth.max_sequence_depth
def max_sequence_depth(comma_sequence, current_depth) # Sequence contains interpolation; assume a depth of 1 return current_depth + 1 unless comma_sequence comma_sequence.members.map { |sequence| sequence_depth(sequence, current_depth) }.max end
ruby
def max_sequence_depth(comma_sequence, current_depth) # Sequence contains interpolation; assume a depth of 1 return current_depth + 1 unless comma_sequence comma_sequence.members.map { |sequence| sequence_depth(sequence, current_depth) }.max end
[ "def", "max_sequence_depth", "(", "comma_sequence", ",", "current_depth", ")", "# Sequence contains interpolation; assume a depth of 1", "return", "current_depth", "+", "1", "unless", "comma_sequence", "comma_sequence", ".", "members", ".", "map", "{", "|", "sequence", "|", "sequence_depth", "(", "sequence", ",", "current_depth", ")", "}", ".", "max", "end" ]
Find the maximum depth of all sequences in a comma sequence.
[ "Find", "the", "maximum", "depth", "of", "all", "sequences", "in", "a", "comma", "sequence", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/selector_depth.rb#L29-L34
11,169
sds/scss-lint
lib/scss_lint/linter/indentation.rb
SCSSLint.Linter::Indentation.check_root_ruleset_indent
def check_root_ruleset_indent(node, actual_indent) # Whether node is a ruleset not nested within any other ruleset. if @indent == 0 && node.is_a?(Sass::Tree::RuleNode) unless actual_indent % @indent_width == 0 add_lint(node.line, lint_message("a multiple of #{@indent_width}", actual_indent)) return true end end false end
ruby
def check_root_ruleset_indent(node, actual_indent) # Whether node is a ruleset not nested within any other ruleset. if @indent == 0 && node.is_a?(Sass::Tree::RuleNode) unless actual_indent % @indent_width == 0 add_lint(node.line, lint_message("a multiple of #{@indent_width}", actual_indent)) return true end end false end
[ "def", "check_root_ruleset_indent", "(", "node", ",", "actual_indent", ")", "# Whether node is a ruleset not nested within any other ruleset.", "if", "@indent", "==", "0", "&&", "node", ".", "is_a?", "(", "Sass", "::", "Tree", "::", "RuleNode", ")", "unless", "actual_indent", "%", "@indent_width", "==", "0", "add_lint", "(", "node", ".", "line", ",", "lint_message", "(", "\"a multiple of #{@indent_width}\"", ",", "actual_indent", ")", ")", "return", "true", "end", "end", "false", "end" ]
Allow rulesets to be indented any amount when the indent is zero, as long as it's a multiple of the indent width
[ "Allow", "rulesets", "to", "be", "indented", "any", "amount", "when", "the", "indent", "is", "zero", "as", "long", "as", "it", "s", "a", "multiple", "of", "the", "indent", "width" ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/indentation.rb#L166-L176
11,170
sds/scss-lint
lib/scss_lint/linter/indentation.rb
SCSSLint.Linter::Indentation.one_shift_greater_than_parent?
def one_shift_greater_than_parent?(node, actual_indent) parent_indent = node_indent(node_indent_parent(node)).length expected_indent = parent_indent + @indent_width expected_indent == actual_indent end
ruby
def one_shift_greater_than_parent?(node, actual_indent) parent_indent = node_indent(node_indent_parent(node)).length expected_indent = parent_indent + @indent_width expected_indent == actual_indent end
[ "def", "one_shift_greater_than_parent?", "(", "node", ",", "actual_indent", ")", "parent_indent", "=", "node_indent", "(", "node_indent_parent", "(", "node", ")", ")", ".", "length", "expected_indent", "=", "parent_indent", "+", "@indent_width", "expected_indent", "==", "actual_indent", "end" ]
Returns whether node is indented exactly one indent width greater than its parent. @param node [Sass::Tree::Node] @return [true,false]
[ "Returns", "whether", "node", "is", "indented", "exactly", "one", "indent", "width", "greater", "than", "its", "parent", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/indentation.rb#L183-L187
11,171
sds/scss-lint
lib/scss_lint/linter/space_between_parens.rb
SCSSLint.Linter::SpaceBetweenParens.feel_for_enclosing_parens
def feel_for_enclosing_parens(node) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity range = node.source_range original_source = source_from_range(range) left_offset = -1 right_offset = 0 if original_source[-1] != ')' right_offset += 1 while character_at(range.end_pos, right_offset) =~ /\s/ return original_source if character_at(range.end_pos, right_offset) != ')' end # At this point, we know that we're wrapped on the right by a ')'. # Are we wrapped on the left by a '('? left_offset -= 1 while character_at(range.start_pos, left_offset) =~ /\s/ return original_source if character_at(range.start_pos, left_offset) != '(' # At this point, we know we're wrapped on both sides by parens. However, # those parens may be part of a parent function call. We don't care about # such parens. This depends on whether the preceding character is part of # a function name. return original_source if character_at(range.start_pos, left_offset - 1).match?(/[A-Za-z0-9_]/) range.start_pos.offset += left_offset range.end_pos.offset += right_offset source_from_range(range) end
ruby
def feel_for_enclosing_parens(node) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity range = node.source_range original_source = source_from_range(range) left_offset = -1 right_offset = 0 if original_source[-1] != ')' right_offset += 1 while character_at(range.end_pos, right_offset) =~ /\s/ return original_source if character_at(range.end_pos, right_offset) != ')' end # At this point, we know that we're wrapped on the right by a ')'. # Are we wrapped on the left by a '('? left_offset -= 1 while character_at(range.start_pos, left_offset) =~ /\s/ return original_source if character_at(range.start_pos, left_offset) != '(' # At this point, we know we're wrapped on both sides by parens. However, # those parens may be part of a parent function call. We don't care about # such parens. This depends on whether the preceding character is part of # a function name. return original_source if character_at(range.start_pos, left_offset - 1).match?(/[A-Za-z0-9_]/) range.start_pos.offset += left_offset range.end_pos.offset += right_offset source_from_range(range) end
[ "def", "feel_for_enclosing_parens", "(", "node", ")", "# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity", "range", "=", "node", ".", "source_range", "original_source", "=", "source_from_range", "(", "range", ")", "left_offset", "=", "-", "1", "right_offset", "=", "0", "if", "original_source", "[", "-", "1", "]", "!=", "')'", "right_offset", "+=", "1", "while", "character_at", "(", "range", ".", "end_pos", ",", "right_offset", ")", "=~", "/", "\\s", "/", "return", "original_source", "if", "character_at", "(", "range", ".", "end_pos", ",", "right_offset", ")", "!=", "')'", "end", "# At this point, we know that we're wrapped on the right by a ')'.", "# Are we wrapped on the left by a '('?", "left_offset", "-=", "1", "while", "character_at", "(", "range", ".", "start_pos", ",", "left_offset", ")", "=~", "/", "\\s", "/", "return", "original_source", "if", "character_at", "(", "range", ".", "start_pos", ",", "left_offset", ")", "!=", "'('", "# At this point, we know we're wrapped on both sides by parens. However,", "# those parens may be part of a parent function call. We don't care about", "# such parens. This depends on whether the preceding character is part of", "# a function name.", "return", "original_source", "if", "character_at", "(", "range", ".", "start_pos", ",", "left_offset", "-", "1", ")", ".", "match?", "(", "/", "/", ")", "range", ".", "start_pos", ".", "offset", "+=", "left_offset", "range", ".", "end_pos", ".", "offset", "+=", "right_offset", "source_from_range", "(", "range", ")", "end" ]
An expression enclosed in parens will include or not include each paren, depending on whitespace. Here we feel out for enclosing parens, and return them as the new source for the node.
[ "An", "expression", "enclosed", "in", "parens", "will", "include", "or", "not", "include", "each", "paren", "depending", "on", "whitespace", ".", "Here", "we", "feel", "out", "for", "enclosing", "parens", "and", "return", "them", "as", "the", "new", "source", "for", "the", "node", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/space_between_parens.rb#L72-L98
11,172
sds/scss-lint
lib/scss_lint/linter/empty_line_between_blocks.rb
SCSSLint.Linter::EmptyLineBetweenBlocks.check_preceding_node
def check_preceding_node(node, type) case prev_node(node) when nil, Sass::Tree::FunctionNode, Sass::Tree::MixinNode, Sass::Tree::MixinDefNode, Sass::Tree::RuleNode, Sass::Tree::CommentNode # Ignore nil else unless engine.lines[node.line - 2].strip.empty? add_lint(node.line, MESSAGE_FORMAT % [type, 'preceded']) end end end
ruby
def check_preceding_node(node, type) case prev_node(node) when nil, Sass::Tree::FunctionNode, Sass::Tree::MixinNode, Sass::Tree::MixinDefNode, Sass::Tree::RuleNode, Sass::Tree::CommentNode # Ignore nil else unless engine.lines[node.line - 2].strip.empty? add_lint(node.line, MESSAGE_FORMAT % [type, 'preceded']) end end end
[ "def", "check_preceding_node", "(", "node", ",", "type", ")", "case", "prev_node", "(", "node", ")", "when", "nil", ",", "Sass", "::", "Tree", "::", "FunctionNode", ",", "Sass", "::", "Tree", "::", "MixinNode", ",", "Sass", "::", "Tree", "::", "MixinDefNode", ",", "Sass", "::", "Tree", "::", "RuleNode", ",", "Sass", "::", "Tree", "::", "CommentNode", "# Ignore", "nil", "else", "unless", "engine", ".", "lines", "[", "node", ".", "line", "-", "2", "]", ".", "strip", ".", "empty?", "add_lint", "(", "node", ".", "line", ",", "MESSAGE_FORMAT", "%", "[", "type", ",", "'preceded'", "]", ")", "end", "end", "end" ]
In cases where the previous node is not a block declaration, we won't have run any checks against it, so we need to check here if the previous line is an empty line
[ "In", "cases", "where", "the", "previous", "node", "is", "not", "a", "block", "declaration", "we", "won", "t", "have", "run", "any", "checks", "against", "it", "so", "we", "need", "to", "check", "here", "if", "the", "previous", "line", "is", "an", "empty", "line" ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/empty_line_between_blocks.rb#L80-L96
11,173
sds/scss-lint
lib/scss_lint/linter/space_after_property_colon.rb
SCSSLint.Linter::SpaceAfterPropertyColon.value_offset
def value_offset(prop) src_range = prop.name_source_range src_range.start_pos.offset + (src_range.end_pos.offset - src_range.start_pos.offset) + whitespace_after_colon(prop).take_while { |w| w == ' ' }.size end
ruby
def value_offset(prop) src_range = prop.name_source_range src_range.start_pos.offset + (src_range.end_pos.offset - src_range.start_pos.offset) + whitespace_after_colon(prop).take_while { |w| w == ' ' }.size end
[ "def", "value_offset", "(", "prop", ")", "src_range", "=", "prop", ".", "name_source_range", "src_range", ".", "start_pos", ".", "offset", "+", "(", "src_range", ".", "end_pos", ".", "offset", "-", "src_range", ".", "start_pos", ".", "offset", ")", "+", "whitespace_after_colon", "(", "prop", ")", ".", "take_while", "{", "|", "w", "|", "w", "==", "' '", "}", ".", "size", "end" ]
Offset of value for property
[ "Offset", "of", "value", "for", "property" ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/space_after_property_colon.rb#L75-L80
11,174
sds/scss-lint
lib/scss_lint/rake_task.rb
SCSSLint.RakeTask.default_description
def default_description description = 'Run `scss-lint' description += " --config #{config}" if config description += " #{args}" if args description += " #{files.join(' ')}" if files.any? description += ' [files...]`' description end
ruby
def default_description description = 'Run `scss-lint' description += " --config #{config}" if config description += " #{args}" if args description += " #{files.join(' ')}" if files.any? description += ' [files...]`' description end
[ "def", "default_description", "description", "=", "'Run `scss-lint'", "description", "+=", "\" --config #{config}\"", "if", "config", "description", "+=", "\" #{args}\"", "if", "args", "description", "+=", "\" #{files.join(' ')}\"", "if", "files", ".", "any?", "description", "+=", "' [files...]`'", "description", "end" ]
Friendly description that shows the full command that will be executed.
[ "Friendly", "description", "that", "shows", "the", "full", "command", "that", "will", "be", "executed", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/rake_task.rb#L115-L122
11,175
sds/scss-lint
lib/scss_lint/cli.rb
SCSSLint.CLI.run
def run(args) options = SCSSLint::Options.new.parse(args) act_on_options(options) rescue StandardError => e handle_runtime_exception(e, options) end
ruby
def run(args) options = SCSSLint::Options.new.parse(args) act_on_options(options) rescue StandardError => e handle_runtime_exception(e, options) end
[ "def", "run", "(", "args", ")", "options", "=", "SCSSLint", "::", "Options", ".", "new", ".", "parse", "(", "args", ")", "act_on_options", "(", "options", ")", "rescue", "StandardError", "=>", "e", "handle_runtime_exception", "(", "e", ",", "options", ")", "end" ]
Create a CLI that outputs to the specified logger. @param logger [SCSSLint::Logger]
[ "Create", "a", "CLI", "that", "outputs", "to", "the", "specified", "logger", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/cli.rb#L31-L36
11,176
sds/scss-lint
lib/scss_lint/cli.rb
SCSSLint.CLI.relevant_configuration_file
def relevant_configuration_file(options) if options[:config_file] options[:config_file] elsif File.exist?(Config::FILE_NAME) Config::FILE_NAME elsif File.exist?(Config.user_file) Config.user_file end end
ruby
def relevant_configuration_file(options) if options[:config_file] options[:config_file] elsif File.exist?(Config::FILE_NAME) Config::FILE_NAME elsif File.exist?(Config.user_file) Config.user_file end end
[ "def", "relevant_configuration_file", "(", "options", ")", "if", "options", "[", ":config_file", "]", "options", "[", ":config_file", "]", "elsif", "File", ".", "exist?", "(", "Config", "::", "FILE_NAME", ")", "Config", "::", "FILE_NAME", "elsif", "File", ".", "exist?", "(", "Config", ".", "user_file", ")", "Config", ".", "user_file", "end", "end" ]
Return the path of the configuration file that should be loaded. @param options [Hash] @return [String]
[ "Return", "the", "path", "of", "the", "configuration", "file", "that", "should", "be", "loaded", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/cli.rb#L151-L159
11,177
sds/scss-lint
lib/scss_lint/sass/tree.rb
Sass::Tree.Node.add_line_number
def add_line_number(node) node.line ||= line if node.is_a?(::Sass::Script::Tree::Node) node end
ruby
def add_line_number(node) node.line ||= line if node.is_a?(::Sass::Script::Tree::Node) node end
[ "def", "add_line_number", "(", "node", ")", "node", ".", "line", "||=", "line", "if", "node", ".", "is_a?", "(", "::", "Sass", "::", "Script", "::", "Tree", "::", "Node", ")", "node", "end" ]
The Sass parser sometimes doesn't assign line numbers in cases where it should. This is a helper to easily correct that.
[ "The", "Sass", "parser", "sometimes", "doesn", "t", "assign", "line", "numbers", "in", "cases", "where", "it", "should", ".", "This", "is", "a", "helper", "to", "easily", "correct", "that", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/sass/tree.rb#L16-L19
11,178
sds/scss-lint
lib/scss_lint/linter.rb
SCSSLint.Linter.run
def run(engine, config) @lints = [] @config = config @engine = engine @comment_processor = ControlCommentProcessor.new(self) visit(engine.tree) @lints = @comment_processor.filter_lints(@lints) end
ruby
def run(engine, config) @lints = [] @config = config @engine = engine @comment_processor = ControlCommentProcessor.new(self) visit(engine.tree) @lints = @comment_processor.filter_lints(@lints) end
[ "def", "run", "(", "engine", ",", "config", ")", "@lints", "=", "[", "]", "@config", "=", "config", "@engine", "=", "engine", "@comment_processor", "=", "ControlCommentProcessor", ".", "new", "(", "self", ")", "visit", "(", "engine", ".", "tree", ")", "@lints", "=", "@comment_processor", ".", "filter_lints", "(", "@lints", ")", "end" ]
Create a linter. Run this linter against a parsed document with the given configuration, returning the lints that were found. @param engine [Engine] @param config [Config] @return [Array<Lint>]
[ "Create", "a", "linter", ".", "Run", "this", "linter", "against", "a", "parsed", "document", "with", "the", "given", "configuration", "returning", "the", "lints", "that", "were", "found", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L36-L43
11,179
sds/scss-lint
lib/scss_lint/linter.rb
SCSSLint.Linter.add_lint
def add_lint(node_or_line_or_location, message) @lints << Lint.new(self, engine.filename, extract_location(node_or_line_or_location), message, @config.fetch('severity', :warning).to_sym) end
ruby
def add_lint(node_or_line_or_location, message) @lints << Lint.new(self, engine.filename, extract_location(node_or_line_or_location), message, @config.fetch('severity', :warning).to_sym) end
[ "def", "add_lint", "(", "node_or_line_or_location", ",", "message", ")", "@lints", "<<", "Lint", ".", "new", "(", "self", ",", "engine", ".", "filename", ",", "extract_location", "(", "node_or_line_or_location", ")", ",", "message", ",", "@config", ".", "fetch", "(", "'severity'", ",", ":warning", ")", ".", "to_sym", ")", "end" ]
Helper for creating lint from a parse tree node @param node_or_line_or_location [Sass::Script::Tree::Node, Fixnum, SCSSLint::Location, Sass::Source::Position] @param message [String]
[ "Helper", "for", "creating", "lint", "from", "a", "parse", "tree", "node" ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L58-L64
11,180
sds/scss-lint
lib/scss_lint/linter.rb
SCSSLint.Linter.source_from_range
def source_from_range(source_range) # rubocop:disable Metrics/AbcSize current_line = source_range.start_pos.line - 1 last_line = source_range.end_pos.line - 1 start_pos = source_range.start_pos.offset - 1 source = if current_line == last_line engine.lines[current_line][start_pos..(source_range.end_pos.offset - 1)] else engine.lines[current_line][start_pos..-1] end current_line += 1 while current_line < last_line source += engine.lines[current_line].to_s current_line += 1 end if source_range.start_pos.line != source_range.end_pos.line source += ((engine.lines[current_line] || '')[0...source_range.end_pos.offset]).to_s end source end
ruby
def source_from_range(source_range) # rubocop:disable Metrics/AbcSize current_line = source_range.start_pos.line - 1 last_line = source_range.end_pos.line - 1 start_pos = source_range.start_pos.offset - 1 source = if current_line == last_line engine.lines[current_line][start_pos..(source_range.end_pos.offset - 1)] else engine.lines[current_line][start_pos..-1] end current_line += 1 while current_line < last_line source += engine.lines[current_line].to_s current_line += 1 end if source_range.start_pos.line != source_range.end_pos.line source += ((engine.lines[current_line] || '')[0...source_range.end_pos.offset]).to_s end source end
[ "def", "source_from_range", "(", "source_range", ")", "# rubocop:disable Metrics/AbcSize", "current_line", "=", "source_range", ".", "start_pos", ".", "line", "-", "1", "last_line", "=", "source_range", ".", "end_pos", ".", "line", "-", "1", "start_pos", "=", "source_range", ".", "start_pos", ".", "offset", "-", "1", "source", "=", "if", "current_line", "==", "last_line", "engine", ".", "lines", "[", "current_line", "]", "[", "start_pos", "..", "(", "source_range", ".", "end_pos", ".", "offset", "-", "1", ")", "]", "else", "engine", ".", "lines", "[", "current_line", "]", "[", "start_pos", "..", "-", "1", "]", "end", "current_line", "+=", "1", "while", "current_line", "<", "last_line", "source", "+=", "engine", ".", "lines", "[", "current_line", "]", ".", "to_s", "current_line", "+=", "1", "end", "if", "source_range", ".", "start_pos", ".", "line", "!=", "source_range", ".", "end_pos", ".", "line", "source", "+=", "(", "(", "engine", ".", "lines", "[", "current_line", "]", "||", "''", ")", "[", "0", "...", "source_range", ".", "end_pos", ".", "offset", "]", ")", ".", "to_s", "end", "source", "end" ]
Extracts the original source code given a range. @param source_range [Sass::Source::Range] @return [String] the original source code
[ "Extracts", "the", "original", "source", "code", "given", "a", "range", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L89-L112
11,181
sds/scss-lint
lib/scss_lint/linter.rb
SCSSLint.Linter.node_on_single_line?
def node_on_single_line?(node) return if node.source_range.start_pos.line != node.source_range.end_pos.line # The Sass parser reports an incorrect source range if the trailing curly # brace is on the next line, e.g. # # p { # } # # Since we don't want to count this as a single line node, check if the # last character on the first line is an opening curly brace. engine.lines[node.line - 1].strip[-1] != '{' end
ruby
def node_on_single_line?(node) return if node.source_range.start_pos.line != node.source_range.end_pos.line # The Sass parser reports an incorrect source range if the trailing curly # brace is on the next line, e.g. # # p { # } # # Since we don't want to count this as a single line node, check if the # last character on the first line is an opening curly brace. engine.lines[node.line - 1].strip[-1] != '{' end
[ "def", "node_on_single_line?", "(", "node", ")", "return", "if", "node", ".", "source_range", ".", "start_pos", ".", "line", "!=", "node", ".", "source_range", ".", "end_pos", ".", "line", "# The Sass parser reports an incorrect source range if the trailing curly", "# brace is on the next line, e.g.", "#", "# p {", "# }", "#", "# Since we don't want to count this as a single line node, check if the", "# last character on the first line is an opening curly brace.", "engine", ".", "lines", "[", "node", ".", "line", "-", "1", "]", ".", "strip", "[", "-", "1", "]", "!=", "'{'", "end" ]
Returns whether a given node spans only a single line. @param node [Sass::Tree::Node] @return [true,false] whether the node spans a single line
[ "Returns", "whether", "a", "given", "node", "spans", "only", "a", "single", "line", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L118-L130
11,182
sds/scss-lint
lib/scss_lint/linter.rb
SCSSLint.Linter.visit
def visit(node) # Visit the selector of a rule if parsed rules are available if node.is_a?(Sass::Tree::RuleNode) && node.parsed_rules visit_selector(node.parsed_rules) end @comment_processor.before_node_visit(node) if @engine.any_control_commands super @comment_processor.after_node_visit(node) if @engine.any_control_commands end
ruby
def visit(node) # Visit the selector of a rule if parsed rules are available if node.is_a?(Sass::Tree::RuleNode) && node.parsed_rules visit_selector(node.parsed_rules) end @comment_processor.before_node_visit(node) if @engine.any_control_commands super @comment_processor.after_node_visit(node) if @engine.any_control_commands end
[ "def", "visit", "(", "node", ")", "# Visit the selector of a rule if parsed rules are available", "if", "node", ".", "is_a?", "(", "Sass", "::", "Tree", "::", "RuleNode", ")", "&&", "node", ".", "parsed_rules", "visit_selector", "(", "node", ".", "parsed_rules", ")", "end", "@comment_processor", ".", "before_node_visit", "(", "node", ")", "if", "@engine", ".", "any_control_commands", "super", "@comment_processor", ".", "after_node_visit", "(", "node", ")", "if", "@engine", ".", "any_control_commands", "end" ]
Modified so we can also visit selectors in linters @param node [Sass::Tree::Node, Sass::Script::Tree::Node, Sass::Script::Value::Base]
[ "Modified", "so", "we", "can", "also", "visit", "selectors", "in", "linters" ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L136-L145
11,183
sds/scss-lint
lib/scss_lint/linter.rb
SCSSLint.Linter.visit_children
def visit_children(parent) parent.children.each do |child| child.node_parent = parent visit(child) end end
ruby
def visit_children(parent) parent.children.each do |child| child.node_parent = parent visit(child) end end
[ "def", "visit_children", "(", "parent", ")", "parent", ".", "children", ".", "each", "do", "|", "child", "|", "child", ".", "node_parent", "=", "parent", "visit", "(", "child", ")", "end", "end" ]
Redefine so we can set the `node_parent` of each node @param parent [Sass::Tree::Node, Sass::Script::Tree::Node, Sass::Script::Value::Base]
[ "Redefine", "so", "we", "can", "set", "the", "node_parent", "of", "each", "node" ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter.rb#L151-L156
11,184
sds/scss-lint
lib/scss_lint/linter/space_after_comma.rb
SCSSLint.Linter::SpaceAfterComma.sort_args_by_position
def sort_args_by_position(*args) args.flatten.compact.sort_by do |arg| pos = arg.source_range.end_pos [pos.line, pos.offset] end end
ruby
def sort_args_by_position(*args) args.flatten.compact.sort_by do |arg| pos = arg.source_range.end_pos [pos.line, pos.offset] end end
[ "def", "sort_args_by_position", "(", "*", "args", ")", "args", ".", "flatten", ".", "compact", ".", "sort_by", "do", "|", "arg", "|", "pos", "=", "arg", ".", "source_range", ".", "end_pos", "[", "pos", ".", "line", ",", "pos", ".", "offset", "]", "end", "end" ]
Since keyword arguments are not guaranteed to be in order, use the source range to order arguments so we check them in the order they were declared.
[ "Since", "keyword", "arguments", "are", "not", "guaranteed", "to", "be", "in", "order", "use", "the", "source", "range", "to", "order", "arguments", "so", "we", "check", "them", "in", "the", "order", "they", "were", "declared", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/space_after_comma.rb#L55-L60
11,185
sds/scss-lint
lib/scss_lint/linter/space_after_comma.rb
SCSSLint.Linter::SpaceAfterComma.find_comma_position
def find_comma_position(arg) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity offset = 0 pos = arg.source_range.end_pos if character_at(pos, offset) != ',' loop do offset += 1 break if (right_char = character_at(pos, offset)) == ',' offset = -offset break if (left_char = character_at(pos, offset)) == ',' offset = -offset next unless right_char.nil? && left_char.nil? offset = 0 pos = Sass::Source::Position.new(pos.line + 1, 1) break if character_at(pos, offset) == ',' end end Sass::Source::Position.new(pos.line, pos.offset + offset) end
ruby
def find_comma_position(arg) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity offset = 0 pos = arg.source_range.end_pos if character_at(pos, offset) != ',' loop do offset += 1 break if (right_char = character_at(pos, offset)) == ',' offset = -offset break if (left_char = character_at(pos, offset)) == ',' offset = -offset next unless right_char.nil? && left_char.nil? offset = 0 pos = Sass::Source::Position.new(pos.line + 1, 1) break if character_at(pos, offset) == ',' end end Sass::Source::Position.new(pos.line, pos.offset + offset) end
[ "def", "find_comma_position", "(", "arg", ")", "# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity", "offset", "=", "0", "pos", "=", "arg", ".", "source_range", ".", "end_pos", "if", "character_at", "(", "pos", ",", "offset", ")", "!=", "','", "loop", "do", "offset", "+=", "1", "break", "if", "(", "right_char", "=", "character_at", "(", "pos", ",", "offset", ")", ")", "==", "','", "offset", "=", "-", "offset", "break", "if", "(", "left_char", "=", "character_at", "(", "pos", ",", "offset", ")", ")", "==", "','", "offset", "=", "-", "offset", "next", "unless", "right_char", ".", "nil?", "&&", "left_char", ".", "nil?", "offset", "=", "0", "pos", "=", "Sass", "::", "Source", "::", "Position", ".", "new", "(", "pos", ".", "line", "+", "1", ",", "1", ")", "break", "if", "character_at", "(", "pos", ",", "offset", ")", "==", "','", "end", "end", "Sass", "::", "Source", "::", "Position", ".", "new", "(", "pos", ".", "line", ",", "pos", ".", "offset", "+", "offset", ")", "end" ]
Find the comma following this argument. The Sass parser is unpredictable in where it marks the end of the source range. Thus we need to start at the indicated range, and check left and right of that range, gradually moving further outward until we find the comma.
[ "Find", "the", "comma", "following", "this", "argument", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/space_after_comma.rb#L103-L123
11,186
sds/scss-lint
lib/scss_lint/runner.rb
SCSSLint.Runner.run_linter
def run_linter(linter, engine, file_path) return if @config.excluded_file_for_linter?(file_path, linter) @lints += linter.run(engine, @config.linter_options(linter)) end
ruby
def run_linter(linter, engine, file_path) return if @config.excluded_file_for_linter?(file_path, linter) @lints += linter.run(engine, @config.linter_options(linter)) end
[ "def", "run_linter", "(", "linter", ",", "engine", ",", "file_path", ")", "return", "if", "@config", ".", "excluded_file_for_linter?", "(", "file_path", ",", "linter", ")", "@lints", "+=", "linter", ".", "run", "(", "engine", ",", "@config", ".", "linter_options", "(", "linter", ")", ")", "end" ]
For stubbing in tests.
[ "For", "stubbing", "in", "tests", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/runner.rb#L51-L54
11,187
sds/scss-lint
lib/scss_lint/linter/duplicate_property.rb
SCSSLint.Linter::DuplicateProperty.property_key
def property_key(prop) prop_key = prop.name.join prop_value = value_as_string(prop.value.first) # Differentiate between values for different vendor prefixes prop_value.to_s.scan(/^(-[^-]+-.+)/) do |vendor_keyword| prop_key << vendor_keyword.first end prop_key end
ruby
def property_key(prop) prop_key = prop.name.join prop_value = value_as_string(prop.value.first) # Differentiate between values for different vendor prefixes prop_value.to_s.scan(/^(-[^-]+-.+)/) do |vendor_keyword| prop_key << vendor_keyword.first end prop_key end
[ "def", "property_key", "(", "prop", ")", "prop_key", "=", "prop", ".", "name", ".", "join", "prop_value", "=", "value_as_string", "(", "prop", ".", "value", ".", "first", ")", "# Differentiate between values for different vendor prefixes", "prop_value", ".", "to_s", ".", "scan", "(", "/", "/", ")", "do", "|", "vendor_keyword", "|", "prop_key", "<<", "vendor_keyword", ".", "first", "end", "prop_key", "end" ]
Returns a key identifying the bucket this property and value correspond to for purposes of uniqueness.
[ "Returns", "a", "key", "identifying", "the", "bucket", "this", "property", "and", "value", "correspond", "to", "for", "purposes", "of", "uniqueness", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/duplicate_property.rb#L44-L54
11,188
sds/scss-lint
lib/scss_lint/linter/space_before_brace.rb
SCSSLint.Linter::SpaceBeforeBrace.newline_before_nonwhitespace
def newline_before_nonwhitespace(string) offset = -2 while /\S/.match(string[offset]).nil? return true if string[offset] == "\n" offset -= 1 end false end
ruby
def newline_before_nonwhitespace(string) offset = -2 while /\S/.match(string[offset]).nil? return true if string[offset] == "\n" offset -= 1 end false end
[ "def", "newline_before_nonwhitespace", "(", "string", ")", "offset", "=", "-", "2", "while", "/", "\\S", "/", ".", "match", "(", "string", "[", "offset", "]", ")", ".", "nil?", "return", "true", "if", "string", "[", "offset", "]", "==", "\"\\n\"", "offset", "-=", "1", "end", "false", "end" ]
Check if, starting from the end of a string and moving backwards, towards the beginning, we find a new line before any non-whitespace characters
[ "Check", "if", "starting", "from", "the", "end", "of", "a", "string", "and", "moving", "backwards", "towards", "the", "beginning", "we", "find", "a", "new", "line", "before", "any", "non", "-", "whitespace", "characters" ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/space_before_brace.rb#L67-L74
11,189
sds/scss-lint
lib/scss_lint/linter/single_line_per_selector.rb
SCSSLint.Linter::SingleLinePerSelector.check_multiline_sequence
def check_multiline_sequence(node, sequence, index) return unless sequence.members.size > 1 return unless sequence.members[2..-1].any? { |member| member == "\n" } add_lint(node.line + index, MESSAGE) end
ruby
def check_multiline_sequence(node, sequence, index) return unless sequence.members.size > 1 return unless sequence.members[2..-1].any? { |member| member == "\n" } add_lint(node.line + index, MESSAGE) end
[ "def", "check_multiline_sequence", "(", "node", ",", "sequence", ",", "index", ")", "return", "unless", "sequence", ".", "members", ".", "size", ">", "1", "return", "unless", "sequence", ".", "members", "[", "2", "..", "-", "1", "]", ".", "any?", "{", "|", "member", "|", "member", "==", "\"\\n\"", "}", "add_lint", "(", "node", ".", "line", "+", "index", ",", "MESSAGE", ")", "end" ]
Checks if an individual sequence is split over multiple lines
[ "Checks", "if", "an", "individual", "sequence", "is", "split", "over", "multiple", "lines" ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/single_line_per_selector.rb#L44-L49
11,190
sds/scss-lint
lib/scss_lint/linter/property_units.rb
SCSSLint.Linter::PropertyUnits.check_units
def check_units(node, property, units) allowed_units = allowed_units_for_property(property) return if allowed_units.include?(units) add_lint(node, "#{units} units not allowed on `#{property}`; must be one of " \ "(#{allowed_units.to_a.sort.join(', ')})") end
ruby
def check_units(node, property, units) allowed_units = allowed_units_for_property(property) return if allowed_units.include?(units) add_lint(node, "#{units} units not allowed on `#{property}`; must be one of " \ "(#{allowed_units.to_a.sort.join(', ')})") end
[ "def", "check_units", "(", "node", ",", "property", ",", "units", ")", "allowed_units", "=", "allowed_units_for_property", "(", "property", ")", "return", "if", "allowed_units", ".", "include?", "(", "units", ")", "add_lint", "(", "node", ",", "\"#{units} units not allowed on `#{property}`; must be one of \"", "\"(#{allowed_units.to_a.sort.join(', ')})\"", ")", "end" ]
Checks if a property value's units are allowed. @param node [Sass::Tree::Node] @param property [String] @param units [String]
[ "Checks", "if", "a", "property", "value", "s", "units", "are", "allowed", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/property_units.rb#L56-L63
11,191
sds/scss-lint
lib/scss_lint/linter/declaration_order.rb
SCSSLint.Linter::DeclarationOrder.check_children_order
def check_children_order(sorted_children, children) sorted_children.each_with_index do |sorted_item, index| next if sorted_item == children[index] add_lint(sorted_item.first.line, "Expected item on line #{sorted_item.first.line} to appear " \ "before line #{children[index].first.line}. #{MESSAGE}") break end end
ruby
def check_children_order(sorted_children, children) sorted_children.each_with_index do |sorted_item, index| next if sorted_item == children[index] add_lint(sorted_item.first.line, "Expected item on line #{sorted_item.first.line} to appear " \ "before line #{children[index].first.line}. #{MESSAGE}") break end end
[ "def", "check_children_order", "(", "sorted_children", ",", "children", ")", "sorted_children", ".", "each_with_index", "do", "|", "sorted_item", ",", "index", "|", "next", "if", "sorted_item", "==", "children", "[", "index", "]", "add_lint", "(", "sorted_item", ".", "first", ".", "line", ",", "\"Expected item on line #{sorted_item.first.line} to appear \"", "\"before line #{children[index].first.line}. #{MESSAGE}\"", ")", "break", "end", "end" ]
Find the child that is out of place
[ "Find", "the", "child", "that", "is", "out", "of", "place" ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/declaration_order.rb#L52-L61
11,192
sds/scss-lint
lib/scss_lint/utils.rb
SCSSLint.Utils.node_ancestor
def node_ancestor(node, levels) while levels > 0 node = node.node_parent return unless node levels -= 1 end node end
ruby
def node_ancestor(node, levels) while levels > 0 node = node.node_parent return unless node levels -= 1 end node end
[ "def", "node_ancestor", "(", "node", ",", "levels", ")", "while", "levels", ">", "0", "node", "=", "node", ".", "node_parent", "return", "unless", "node", "levels", "-=", "1", "end", "node", "end" ]
Return nth-ancestor of a node, where 1 is the parent, 2 is grandparent, etc. @param node [Sass::Tree::Node, Sass::Script::Tree::Node] @param level [Integer] @return [Sass::Tree::Node, Sass::Script::Tree::Node, nil]
[ "Return", "nth", "-", "ancestor", "of", "a", "node", "where", "1", "is", "the", "parent", "2", "is", "grandparent", "etc", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/utils.rb#L100-L108
11,193
sds/scss-lint
lib/scss_lint/linter/property_sort_order.rb
SCSSLint.Linter::PropertySortOrder.ignore_property?
def ignore_property?(prop_node) return true if prop_node.name.any? { |part| !part.is_a?(String) } config['ignore_unspecified'] && @preferred_order && !@preferred_order.include?(prop_node.name.join) end
ruby
def ignore_property?(prop_node) return true if prop_node.name.any? { |part| !part.is_a?(String) } config['ignore_unspecified'] && @preferred_order && !@preferred_order.include?(prop_node.name.join) end
[ "def", "ignore_property?", "(", "prop_node", ")", "return", "true", "if", "prop_node", ".", "name", ".", "any?", "{", "|", "part", "|", "!", "part", ".", "is_a?", "(", "String", ")", "}", "config", "[", "'ignore_unspecified'", "]", "&&", "@preferred_order", "&&", "!", "@preferred_order", ".", "include?", "(", "prop_node", ".", "name", ".", "join", ")", "end" ]
Return whether to ignore a property in the sort order. This includes: - properties containing interpolation - properties not explicitly defined in the sort order (if ignore_unspecified is set)
[ "Return", "whether", "to", "ignore", "a", "property", "in", "the", "sort", "order", "." ]
e99afe4ede041a431a06e585c12ce82f6ad50116
https://github.com/sds/scss-lint/blob/e99afe4ede041a431a06e585c12ce82f6ad50116/lib/scss_lint/linter/property_sort_order.rb#L182-L188
11,194
CanCanCommunity/cancancan
lib/cancan/conditions_matcher.rb
CanCan.ConditionsMatcher.matches_conditions?
def matches_conditions?(action, subject, attribute = nil, *extra_args) return call_block_with_all(action, subject, extra_args) if @match_all return matches_block_conditions(subject, attribute, *extra_args) if @block return matches_non_block_conditions(subject) unless conditions_empty? true end
ruby
def matches_conditions?(action, subject, attribute = nil, *extra_args) return call_block_with_all(action, subject, extra_args) if @match_all return matches_block_conditions(subject, attribute, *extra_args) if @block return matches_non_block_conditions(subject) unless conditions_empty? true end
[ "def", "matches_conditions?", "(", "action", ",", "subject", ",", "attribute", "=", "nil", ",", "*", "extra_args", ")", "return", "call_block_with_all", "(", "action", ",", "subject", ",", "extra_args", ")", "if", "@match_all", "return", "matches_block_conditions", "(", "subject", ",", "attribute", ",", "extra_args", ")", "if", "@block", "return", "matches_non_block_conditions", "(", "subject", ")", "unless", "conditions_empty?", "true", "end" ]
Matches the block or conditions hash
[ "Matches", "the", "block", "or", "conditions", "hash" ]
b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf
https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/conditions_matcher.rb#L6-L12
11,195
CanCanCommunity/cancancan
lib/cancan/ability.rb
CanCan.Ability.can?
def can?(action, subject, attribute = nil, *extra_args) match = extract_subjects(subject).lazy.map do |a_subject| relevant_rules_for_match(action, a_subject).detect do |rule| rule.matches_conditions?(action, a_subject, attribute, *extra_args) && rule.matches_attributes?(attribute) end end.reject(&:nil?).first match ? match.base_behavior : false end
ruby
def can?(action, subject, attribute = nil, *extra_args) match = extract_subjects(subject).lazy.map do |a_subject| relevant_rules_for_match(action, a_subject).detect do |rule| rule.matches_conditions?(action, a_subject, attribute, *extra_args) && rule.matches_attributes?(attribute) end end.reject(&:nil?).first match ? match.base_behavior : false end
[ "def", "can?", "(", "action", ",", "subject", ",", "attribute", "=", "nil", ",", "*", "extra_args", ")", "match", "=", "extract_subjects", "(", "subject", ")", ".", "lazy", ".", "map", "do", "|", "a_subject", "|", "relevant_rules_for_match", "(", "action", ",", "a_subject", ")", ".", "detect", "do", "|", "rule", "|", "rule", ".", "matches_conditions?", "(", "action", ",", "a_subject", ",", "attribute", ",", "extra_args", ")", "&&", "rule", ".", "matches_attributes?", "(", "attribute", ")", "end", "end", ".", "reject", "(", ":nil?", ")", ".", "first", "match", "?", "match", ".", "base_behavior", ":", "false", "end" ]
Check if the user has permission to perform a given action on an object. can? :destroy, @project You can also pass the class instead of an instance (if you don't have one handy). can? :create, Project Nested resources can be passed through a hash, this way conditions which are dependent upon the association will work when using a class. can? :create, @category => Project You can also pass multiple objects to check. You only need to pass a hash following the pattern { :any => [many subjects] }. The behaviour is check if there is a permission on any of the given objects. can? :create, {:any => [Project, Rule]} Any additional arguments will be passed into the "can" block definition. This can be used to pass more information about the user's request for example. can? :create, Project, request.remote_ip can :create, Project do |project, remote_ip| # ... end Not only can you use the can? method in the controller and view (see ControllerAdditions), but you can also call it directly on an ability instance. ability.can? :destroy, @project This makes testing a user's abilities very easy. def test "user can only destroy projects which he owns" user = User.new ability = Ability.new(user) assert ability.can?(:destroy, Project.new(:user => user)) assert ability.cannot?(:destroy, Project.new) end Also see the RSpec Matchers to aid in testing.
[ "Check", "if", "the", "user", "has", "permission", "to", "perform", "a", "given", "action", "on", "an", "object", "." ]
b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf
https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/ability.rb#L74-L81
11,196
CanCanCommunity/cancancan
lib/cancan/ability.rb
CanCan.Ability.can
def can(action = nil, subject = nil, *attributes_and_conditions, &block) add_rule(Rule.new(true, action, subject, *attributes_and_conditions, &block)) end
ruby
def can(action = nil, subject = nil, *attributes_and_conditions, &block) add_rule(Rule.new(true, action, subject, *attributes_and_conditions, &block)) end
[ "def", "can", "(", "action", "=", "nil", ",", "subject", "=", "nil", ",", "*", "attributes_and_conditions", ",", "&", "block", ")", "add_rule", "(", "Rule", ".", "new", "(", "true", ",", "action", ",", "subject", ",", "attributes_and_conditions", ",", "block", ")", ")", "end" ]
Defines which abilities are allowed using two arguments. The first one is the action you're setting the permission for, the second one is the class of object you're setting it on. can :update, Article You can pass an array for either of these parameters to match any one. Here the user has the ability to update or destroy both articles and comments. can [:update, :destroy], [Article, Comment] You can pass :all to match any object and :manage to match any action. Here are some examples. can :manage, :all can :update, :all can :manage, Project You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns. can :read, Project, :active => true, :user_id => user.id See ActiveRecordAdditions#accessible_by for how to use this in database queries. These conditions are also used for initial attributes when building a record in ControllerAdditions#load_resource. If the conditions hash does not give you enough control over defining abilities, you can use a block along with any Ruby code you want. can :update, Project do |project| project.groups.include?(user.group) end If the block returns true then the user has that :update ability for that project, otherwise he will be denied access. The downside to using a block is that it cannot be used to generate conditions for database queries. You can pass custom objects into this "can" method, this is usually done with a symbol and is useful if a class isn't available to define permissions on. can :read, :stats can? :read, :stats # => true IMPORTANT: Neither a hash of conditions nor a block will be used when checking permission on a class. can :update, Project, :priority => 3 can? :update, Project # => true If you pass no arguments to +can+, the action, class, and object will be passed to the block and the block will always be executed. This allows you to override the full behavior if the permissions are defined in an external source such as the database. can do |action, object_class, object| # check the database and return true/false end
[ "Defines", "which", "abilities", "are", "allowed", "using", "two", "arguments", ".", "The", "first", "one", "is", "the", "action", "you", "re", "setting", "the", "permission", "for", "the", "second", "one", "is", "the", "class", "of", "object", "you", "re", "setting", "it", "on", "." ]
b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf
https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/ability.rb#L144-L146
11,197
CanCanCommunity/cancancan
lib/cancan/ability.rb
CanCan.Ability.cannot
def cannot(action = nil, subject = nil, *attributes_and_conditions, &block) add_rule(Rule.new(false, action, subject, *attributes_and_conditions, &block)) end
ruby
def cannot(action = nil, subject = nil, *attributes_and_conditions, &block) add_rule(Rule.new(false, action, subject, *attributes_and_conditions, &block)) end
[ "def", "cannot", "(", "action", "=", "nil", ",", "subject", "=", "nil", ",", "*", "attributes_and_conditions", ",", "&", "block", ")", "add_rule", "(", "Rule", ".", "new", "(", "false", ",", "action", ",", "subject", ",", "attributes_and_conditions", ",", "block", ")", ")", "end" ]
Defines an ability which cannot be done. Accepts the same arguments as "can". can :read, :all cannot :read, Comment A block can be passed just like "can", however if the logic is complex it is recommended to use the "can" method. cannot :read, Product do |product| product.invisible? end
[ "Defines", "an", "ability", "which", "cannot", "be", "done", ".", "Accepts", "the", "same", "arguments", "as", "can", "." ]
b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf
https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/ability.rb#L160-L162
11,198
CanCanCommunity/cancancan
lib/cancan/ability.rb
CanCan.Ability.validate_target
def validate_target(target) error_message = "You can't specify target (#{target}) as alias because it is real action name" raise Error, error_message if aliased_actions.values.flatten.include? target end
ruby
def validate_target(target) error_message = "You can't specify target (#{target}) as alias because it is real action name" raise Error, error_message if aliased_actions.values.flatten.include? target end
[ "def", "validate_target", "(", "target", ")", "error_message", "=", "\"You can't specify target (#{target}) as alias because it is real action name\"", "raise", "Error", ",", "error_message", "if", "aliased_actions", ".", "values", ".", "flatten", ".", "include?", "target", "end" ]
User shouldn't specify targets with names of real actions or it will cause Seg fault
[ "User", "shouldn", "t", "specify", "targets", "with", "names", "of", "real", "actions", "or", "it", "will", "cause", "Seg", "fault" ]
b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf
https://github.com/CanCanCommunity/cancancan/blob/b2e5660c6b9b683fc45b8f425b90c4d06e2f24bf/lib/cancan/ability.rb#L165-L168
11,199
backup/backup
lib/backup/archive.rb
Backup.Archive.perform!
def perform! Logger.info "Creating Archive '#{name}'..." path = File.join(Config.tmp_path, @model.trigger, "archives") FileUtils.mkdir_p(path) pipeline = Pipeline.new with_files_from(paths_to_package) do |files_from| pipeline.add( "#{tar_command} #{tar_options} -cPf -#{tar_root} " \ "#{paths_to_exclude} #{files_from}", tar_success_codes ) extension = "tar" if @model.compressor @model.compressor.compress_with do |command, ext| pipeline << command extension << ext end end pipeline << "#{utility(:cat)} > " \ "'#{File.join(path, "#{name}.#{extension}")}'" pipeline.run end if pipeline.success? Logger.info "Archive '#{name}' Complete!" else raise Error, "Failed to Create Archive '#{name}'\n" + pipeline.error_messages end end
ruby
def perform! Logger.info "Creating Archive '#{name}'..." path = File.join(Config.tmp_path, @model.trigger, "archives") FileUtils.mkdir_p(path) pipeline = Pipeline.new with_files_from(paths_to_package) do |files_from| pipeline.add( "#{tar_command} #{tar_options} -cPf -#{tar_root} " \ "#{paths_to_exclude} #{files_from}", tar_success_codes ) extension = "tar" if @model.compressor @model.compressor.compress_with do |command, ext| pipeline << command extension << ext end end pipeline << "#{utility(:cat)} > " \ "'#{File.join(path, "#{name}.#{extension}")}'" pipeline.run end if pipeline.success? Logger.info "Archive '#{name}' Complete!" else raise Error, "Failed to Create Archive '#{name}'\n" + pipeline.error_messages end end
[ "def", "perform!", "Logger", ".", "info", "\"Creating Archive '#{name}'...\"", "path", "=", "File", ".", "join", "(", "Config", ".", "tmp_path", ",", "@model", ".", "trigger", ",", "\"archives\"", ")", "FileUtils", ".", "mkdir_p", "(", "path", ")", "pipeline", "=", "Pipeline", ".", "new", "with_files_from", "(", "paths_to_package", ")", "do", "|", "files_from", "|", "pipeline", ".", "add", "(", "\"#{tar_command} #{tar_options} -cPf -#{tar_root} \"", "\"#{paths_to_exclude} #{files_from}\"", ",", "tar_success_codes", ")", "extension", "=", "\"tar\"", "if", "@model", ".", "compressor", "@model", ".", "compressor", ".", "compress_with", "do", "|", "command", ",", "ext", "|", "pipeline", "<<", "command", "extension", "<<", "ext", "end", "end", "pipeline", "<<", "\"#{utility(:cat)} > \"", "\"'#{File.join(path, \"#{name}.#{extension}\")}'\"", "pipeline", ".", "run", "end", "if", "pipeline", ".", "success?", "Logger", ".", "info", "\"Archive '#{name}' Complete!\"", "else", "raise", "Error", ",", "\"Failed to Create Archive '#{name}'\\n\"", "+", "pipeline", ".", "error_messages", "end", "end" ]
Adds a new Archive to a Backup Model. Backup::Model.new(:my_backup, 'My Backup') do archive :my_archive do |archive| archive.add 'path/to/archive' archive.add '/another/path/to/archive' archive.exclude 'path/to/exclude' archive.exclude '/another/path/to/exclude' end end All paths added using `add` or `exclude` will be expanded to their full paths from the root of the filesystem. Files will be added to the tar archive using these full paths, and their leading `/` will be preserved (using tar's `-P` option). /path/to/pwd/path/to/archive/... /another/path/to/archive/... When a `root` path is given, paths to add/exclude are taken as relative to the `root` path, unless given as absolute paths. Backup::Model.new(:my_backup, 'My Backup') do archive :my_archive do |archive| archive.root '~/my_data' archive.add 'path/to/archive' archive.add '/another/path/to/archive' archive.exclude 'path/to/exclude' archive.exclude '/another/path/to/exclude' end end This directs `tar` to change directories to the `root` path to create the archive. Unless paths were given as absolute, the paths within the archive will be relative to the `root` path. path/to/archive/... /another/path/to/archive/... For absolute paths added to this archive, the leading `/` will be preserved. Take note that when archives are extracted, leading `/` are stripped by default, so care must be taken when extracting archives with mixed relative/absolute paths.
[ "Adds", "a", "new", "Archive", "to", "a", "Backup", "Model", "." ]
64370f925e859f858766b674717a3dbee0de7a26
https://github.com/backup/backup/blob/64370f925e859f858766b674717a3dbee0de7a26/lib/backup/archive.rb#L65-L98