parse snippet include file locations from route
357935
function(path) {
                var pathParts = this.getPathParts(path),
                    tabs,
                    page;
                if (pathParts.length === 0) {
                    return;
                }
                page = pathParts[0];
                if (!page) {
                    return;
                }
                if (page === 'examples' && pathParts.length > 1) {
                    tabs = [];
                    tabs.push('app/examples/' + pathParts[1] + '.html');
                    tabs.push('app/examples/' + pathParts[1] + '.js');
                    return tabs;
                }
            }
1315931
def run_option_parser(args)
      optparse = OptionParser.new do |opts|
        opts.banner = 'Usage: synvert [project_path]'
        opts.on '-d', '--load SNIPPET_PATHS', 'load custom snippets, snippet paths can be local file path or remote http url' do |snippet_paths|
          @options[:custom_snippet_paths] = snippet_paths.split(',').map(&:strip)
        end
        opts.on '-l', '--list', 'list all available snippets' do
          @options[:command] = 'list'
        end
        opts.on '-o', '--open SNIPPET_NAME', 'Open a snippet' do |snippet_name|
          @options[:command] = 'open'
          @options[:snippet_name] = snippet_name
        end
        opts.on '-q', '--query QUERY', 'query specified snippets' do |query|
          @options[:command] = 'query'
          @options[:query] = query
        end
        opts.on '--skip FILE_PATTERNS', 'skip specified files or directories, separated by comma, e.g. app/models/post.rb,vendor/plugins/**/*.rb' do |file_patterns|
          @options[:skip_file_patterns] = file_patterns.split(',')
        end
        opts.on '-s', '--show SNIPPET_NAME', 'show specified snippet description, SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax' do |snippet_name|
          @options[:command] = 'show'
          @options[:snippet_name] = snippet_name
        end
        opts.on '--sync', 'sync snippets' do
          @options[:command] = 'sync'
        end
        opts.on '-r', '--run SNIPPET_NAMES', 'run specified snippets, each SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax,ruby/new_lambda_syntax' do |snippet_names|
          @options[:snippet_names] = snippet_names.split(',').map(&:strip)
        end
        opts.on '-v', '--version', 'show this version' do
          puts Core::VERSION
          exit
        end
      end
      paths = optparse.parse(args)
      Core::Configuration.instance.set :path, paths.first || Dir.pwd
      if @options[:skip_file_patterns] && !@options[:skip_file_patterns].empty?
        skip_files = @options[:skip_file_patterns].map do |file_pattern|
          full_file_pattern = File.join(Core::Configuration.instance.get(:path), file_pattern)
          Dir.glob(full_file_pattern)
        end.flatten
        Core::Configuration.instance.set :skip_files, skip_files
      end
    end
961099
def include_from_file(records, handle):
    
    ids = set(i.strip() for i in handle)

    for record in records:
        if record.id.strip() in ids:
            yield record
1091548
function extractParams(route, path) {
    var vals = route.regex.exec(path).slice(1), params = {}, i, n;

    for (i = 0, n = route.names.length; i < n; i++) {
      params[route.names[i]] = vals[i];
    }

    return params;
  }
47568
def get_snippet_content(snippet_name, **format_kwargs):
    
    filename = snippet_name + '.snippet'
    snippet_file = os.path.join(SNIPPETS_ROOT, filename)
    if not os.path.isfile(snippet_file):
        raise ValueError('could not find snippet with name ' + filename)
    ret = helpers.get_file_content(snippet_file)
    if format_kwargs:
        ret = ret.format(**format_kwargs)
    return ret
1151685
function parseFile (filePath, fileContent) {
  let config = null
  const extension = path.extname(filePath)

  if (extension === '.yml' || extension === '.yaml') {
    config = yaml.safeLoad(replaceEnvironmentVariables(fileContent))
  } else if (extension === '.js') {
    config = require(path.resolve(filePath)) // eslint-disable-line
  } else if (extension === '.json') {
    config = JSON.parse(replaceEnvironmentVariables(fileContent))
  } else {
    throw new Error(`${extension} is not supported as configuration file`)
  }

  return config
}
877402
function (contents) {
                        files.forEach((file, i) => {
                            context.addFile({
                                path: file,
                                content: contents[i]
                            });
                        });

                        return context;
                    }
403364
def _get_assistants_snippets(path, name):
    ''''''
    result = []
    subdirs = {'assistants': 2, 'snippets': 1} # Values used for stripping leading path tokens

    for loc in subdirs:
        for root, dirs, files in os.walk(os.path.join(path, loc)):
            for filename in [utils.strip_prefix(os.path.join(root, f), path) for f in files]:
                stripped = os.path.sep.join(filename.split(os.path.sep)[subdirs[loc]:])
                if stripped.startswith(os.path.join(name, '')) or stripped == name + '.yaml':
                    result.append(os.path.join('fakeroot', filename))

    return result
135849
def include_route?(route)
      value = false

      unless route.blank? || route.path.spec =~ %r{/rails/info/properties|^/assets}
        # this block looks very busy, but, actually all that is really going on here is we are matching
        # parts of the current route against sitemap_filter data configured via config/routes.rb, then,
        # raising and catching exceptions based on the outcome of each evaluation.
        # the rule is all routes excluded, unless included via some type of filter criteria.

        begin

          DuckMap.logger.debug "\r\n  Route: #{route.verb_symbol} #{route.route_name.ljust(30)} #{route.controller_name} => #{route.action_name}"
          DuckMap.logger.debug route
          DuckMap.logger.debug %(#{"Path:".rjust(30)} #{route.path.spec})

          # we don't want to include routes without a name.
          if route.name.blank?
            unless self.blank_route_name?
              raise RouteNameMissing, "route name blank"
            end
          end

          if match_any?(route.action_name, route.exclude_actions) ||
              match_any?(route.controller_name, route.exclude_controllers) ||
              match_any?(route.name, route.exclude_names) ||
              match_any?(route.verb_symbol, route.exclude_verbs)

            raise DuckmapExclude, "exclude"

          end

          if match_any?(route.action_name, route.include_actions) ||
              match_any?(route.controller_name, route.include_controllers) ||
              match_any?(route.name, route.include_names) ||
              match_any?(route.verb_symbol, route.include_verbs)

            raise DuckmapInclude, "include"

          end

          if match_any?(route.action_name, self.sitemap_filters.current_filter[:exclude][:actions])
            raise ExplicitExclude, "exclude"
          end

          if match_any?(route.verb_symbol, self.sitemap_filters.current_filter[:exclude][:verbs])
            raise ExplicitExclude, "exclude"
          end

          if match_any?(route.controller_name, self.sitemap_filters.current_filter[:exclude][:controllers])
            raise ExplicitExclude, "exclude"
          end

          if match_any?(route.name, self.sitemap_filters.current_filter[:exclude][:names])
            raise ExplicitExclude, "exclude"
          end

          if match_any?(route.action_name, self.sitemap_filters.current_filter[:include][:actions])
            raise ExplicitInclude, "include"
          end

          if match_any?(route.verb_symbol, self.sitemap_filters.current_filter[:include][:verbs])
            raise ExplicitInclude, "include"
          end

          if match_any?(route.controller_name, self.sitemap_filters.current_filter[:include][:controllers])
            raise ExplicitInclude, "include"
          end

          if match_any?(route.name, self.sitemap_filters.current_filter[:include][:names])
            raise ExplicitInclude, "include"
          end

        rescue DuckmapExclude => e
          DuckMap.logger.debug %(#{"Duckmap Exclude".rjust(30)} -> #{e})

          if match_any?(route.action_name, route.include_actions) ||
              match_any?(route.controller_name, route.include_controllers) ||
              match_any?(route.name, route.include_names) ||
              match_any?(route.verb_symbol, route.include_verbs)

            DuckMap.logger.debug %(#{"Duckmap Exclude".rjust(30)} -> included again...)
            value = true
          end

        rescue DuckmapInclude => e
          DuckMap.logger.debug %(#{"Duckmap Include".rjust(30)} -> #{e})
          value = true

        rescue ExplicitExclude => e
          DuckMap.logger.debug %(#{"Explicit Exclude".rjust(30)} -> #{e})

        rescue ExplicitInclude => e
          DuckMap.logger.debug %(#{"Explicit Include".rjust(30)} -> #{e})
          value = true

        rescue RouteNameMissing => e
          DuckMap.logger.debug %(#{"Route Name Missing".rjust(30)} -> #{e})

        rescue Exception => e
          DuckMap.logger.info %(#{"Unknown Exception".rjust(30)} -> #{e})
          DuckMap.logger.info e.backtrace.join("\r\n")
        end

      end

      return value
    end
889268
function expandIncludes(source, rootPath) {
	var matcher = new RegExp("^([\t ]*)include ([^/].*);\n?", "gm");
	var match;
	var expanded = '';
	var after = source;
	var includes = [];
	var lastIndex = 0;
	while (match = matcher.exec(source)) {
		var statement = match[0];
		var indent = match[1];
		var filePath = path.join(rootPath, match[2])
		includes.push(filePath);

		expanded += source.substr(lastIndex, match.index - lastIndex);

		expanded += indent + "## Start Include: " + filePath + "\n";

		try {
			var fileContent = fs.readFileSync(filePath, 'utf8');

			// preserve indentation of the include line
			var indentedContent = singleTrailingNewline(NgindoxUtil.indentBlock(fileContent, indent));

			// recurse with relative path
			expanded += expandIncludes(indentedContent, path.dirname(rootPath));
		} catch (err) {
			// file probably missing
			expanded += indent + "## Error: " + err + "\n";
		}

		expanded += indent + "## End Include: " + filePath + "\n";

		// store end of match as begining of next search
		lastIndex = matcher.lastIndex;
	}

	expanded += source.substr(lastIndex);

	return expanded;
}
892321
def parse_snippet_css(path)
      return unless core.storage.file?(path)
      parser = ::CssParser::Parser.new
      parser.add_block! core.storage.read(path)
      apply_styles parser, "snippet"
    end
1198545
function _parseRoutes(){
		$routes = $this->getConfig('map');
		
		$uri = implode('/',$this->segments);
		// Is have route to vendor?
		if(isset($routes['root:vendor'])){
			$this->app_path = VENDOR_PATH.$routes['root:vendor'];
		}
		elseif(isset($routes[current($this->segments).':vendor'])){
			$this->app_path = VENDOR_PATH.$routes[current($this->segments).':vendor'];
			array_shift($this->segments);
		}
		
		// Is there a literal match?  If so we're done
		elseif (isset($routes[$uri])){
			explode('/', $routes[$uri]);
			return $this->_setRequest(explode('/', $routes[$uri]));
		}
		
		// Loop through the route array looking for wild-cards
		foreach ($routes as $key => $val){
			// Convert wild-cards to RegEx
			$key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));

			// Does the RegEx match?
			if (preg_match('#^'.$key.'$#', $uri))
			{
				// Do we have a back-reference?
				if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE)
				{
					$val = preg_replace('#^'.$key.'$#', $val, $uri);
				}

				return $this->_setRequest(explode('/', $val));
			}
		}

		
		// If we got this far it means we didn't encounter a
		// matching route so we'll set the site default route
		$this->_setRequest($this->segments);
		
	}
711574
function parse_files(files, options, callback) {
  var nodes = {
    // root section node
    '': {
      id: '',
      type: 'section',
      children: [],
      description: '',
      short_description: '',
      href: '#',
      root: true,
      file: '',
      line: 0
    }
  };

  var reportObject = { };
  
  async.forEachSeries(files, function (file, next_file) {
    var fn = parsers[path.extname(file)];

    if (!fn) {
      next_file();
      return;
    }

    console.info('Parsing file: ' + file);
    fn(file, options, function (err, file_nodes, file_report) {
      // TODO:  fail on name clash here as well -- as we might get name clash
      //        from different parsers, or even different files
      _.extend(nodes, file_nodes);
      _.extend(reportObject, file_report);
      next_file(err);
    });
  }, function (err) {
    callback(err, nodes, reportObject);
  });
}
182366
function addMatch (route) {
  let routePath = route.path
  let paramNames = []
  let matched
  // find any paths prefixed with `:` or `%`, and treat them as capture groups
  while ((matched = routePath.match(paramPattern)) !== null) {
    routePath = routePath.replace(paramPattern, '([^?/]+)')
    paramNames.push(matched[1])
  }
  // if a route ends with `index`, allow matching that route without matching the `index` part
  if (path.basename(routePath) === 'index') {
    route.isIndex = true
    routePath = routePath.replace(/\/index$/, '/?([:%]?index)?')
  }
  // create a regex with our path
  let pattern = new RegExp(`^${routePath}(\\?(.*)|$)`, 'i')
  route.pattern = pattern
  route.match = url => {
    let m = url.match(pattern)
    if (m) {
      let params = paramNames.reduce((o, p, idx) => {
        o[p] = m[idx + 1]
        return o
      }, {})
      let query = qs.parse(m[m.length - 1])
      return { params, query }
    }
  }
  return route
}
1018058
def get_snippets(code_list, base=SNIPPET_FOLDER):
    
    output = []
    for code in code_list:
        path = gen_path(base, code)
        fp = os.path.join(path, code)
        try:
            with open(fp) as f:
                output.append(f.read())
        except FileNotFoundError:
            output.append('')
            logging.warning("FileNotFoundError: No such file: %r" % fp )

    return output
288636
def parse_location(data):
    

    tokens = data.split(",")
    location = Location(directories=[], files=[], filters_in=[], filters_out=[], targets=[])
    if not tokens:
        return location

    for token in tokens:
        token = token.strip()
        if not token:
            continue

        if foundations.common.path_exists(token):
            if os.path.isdir(token):
                location.directories.append(token)
            else:
                location.files.append(token)
        else:
            match = re.match("(?P<filterIn>\*\.\w+)", token)
            if match:
                location.filters_in.append(fnmatch.translate(match.group("filterIn")))
                continue
            match = re.match("!(?P<filterOut>\*\.\w+)", token)
            if match:
                location.filters_out.append(fnmatch.translate(match.group("filterOut")))
                continue
            match = re.match("\<(?P<target>[\w ]+)\>", token)
            if match:
                location.targets.append(match.group("target"))
                continue
    return location
957706
function findI18nKeysAndStrings(filePath) {
    const textContentRegEx = /data-i18n="(.*?)".*?>\s*(.*?)\s*</gs;
    const placeholderRegEx = /data-i18n-placeholder="(.*?)"(?:.*?placeholder="(.*?)")?/g;
    const phraseRegEx = /translatePhrase\('(.*?)'\)/g;

    // Get global variable
    const contents = fs.readFileSync(filePath).toString();

    /** @type {object} */
    const dict = {};

    let textMatch;
    while ((textMatch = textContentRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign
        const key = textMatch[1];
        const phrase = textMatch[2];
        dict[key] = phrase;
    }

    let placeholderMatch;
    while ((placeholderMatch = placeholderRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign
        const key = placeholderMatch[1];
        const phrase = placeholderMatch[2] || '- not found -';
        dict[key] = phrase;
    }

    let phraseMatch;
    while ((phraseMatch = phraseRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign
        const key = phraseMatch[1];
        const phrase = false;
        dict[key] = phrase;
    }

    return dict;
}