Shell variable substitution code taken from 'somewhere'?

Not sure who :(
This will be cleaned up at some point anyway
433819
function substiteVariable(variable, options, cb) {
    var value;
    var err = null;
    var s = variable.split(':', 2);
    if (s.length == 2) {
        value = options.env[s[0]];
        if (typeof value == 'function') {
            value = value();
        }
        if (s[1][0] == '+') {
            // Substitute replacement, but only if variable is defined and nonempty. Otherwise, substitute nothing
            value = value ? s[1].substring(1) : '';
        } else if (s[1][0] == '-') {
            // Substitute the value of variable, but if that is empty or undefined, use default instead
            value = value || s[1].substring(1);
        } else if (s[1][0] == '#') {
            // Substitute with the length of the value of the variable
            value = value !== undefined ? String(value).length : 0;
        } else if (s[1][0] == '=') {
            // Substitute the value of variable, but if that is empty or undefined, use default instead and set the variable to default
            if (!value) {
                value = s[1].substring(1);
                options.env[s[0]] = value;
            }
        } else if (s[1][0] == '?') {
            // If variable is defined and not empty, substitute its value. Otherwise, print message as an error message.
            if (!value) {
                if (s[1].length > 1) {
                    throw new Error();
                    // return cb(s[0] + ': ' + s[1].substring(1));
                } else {
                    throw new Error();
                    // return cb(s[0] + ': parameter null or not set');
                }
            }
        }
    } else {
        value = options.env[variable];
        if (typeof value == 'function') {
            value = value();
        }
    }
    return value;
}
1040328
function substituteVars(rawText, vars)
{
    if (!vars)
    {
        return rawText;
    }
    //after loading contents, perform variable substitution
    Object.keys(vars).forEach(function (varName)
    {
        if (vars.hasOwnProperty(varName))
        {
            var varValue = vars[varName];
            rawText = replaceAll(rawText, varName, varValue);
        }
    });
    return rawText;
}
1121380
def _resolve_variable(cls, config, substitution):
        
        variable = substitution.variable
        try:
            return True, config.get(variable)
        except ConfigMissingException:
            # default to environment variable
            value = os.environ.get(variable)

            if value is None:
                if substitution.optional:
                    return False, None
                else:
                    raise ConfigSubstitutionException(
                        "Cannot resolve variable ${{{variable}}} (line: {line}, col: {col})".format(
                            variable=variable,
                            line=lineno(substitution.loc, substitution.instring),
                            col=col(substitution.loc, substitution.instring)))
            elif isinstance(value, ConfigList) or isinstance(value, ConfigTree):
                raise ConfigSubstitutionException(
                    "Cannot substitute variable ${{{variable}}} because it does not point to a "
                    "string, int, float, boolean or null {type} (line:{line}, col: {col})".format(
                        variable=variable,
                        type=value.__class__.__name__,
                        line=lineno(substitution.loc, substitution.instring),
                        col=col(substitution.loc, substitution.instring)))
            return True, value
819727
function variables(root, config, done) {
  var expression = /\$v\[(.+?)\]/g;
  each(Object.keys(root), function(key, next) {
    var value = root[key];
    if (typeof value === 'object') return variables(value, config, next);
    if (typeof value !== 'string') return next();
    root[key] = value.replace(expression, function(match, matchKey) {
      return config[matchKey] || match;
    });
    next();
  }, done);
}
676359
function replacePlaceholders(src, options) {
	return Object.keys(placeholders).reduce((out, placeholder) => {
		return out.replace(new RegExp(`${placeholder}`, 'g'), placeholders[placeholder]);
	}, src);
}
1148557
private static function ReplaceVars(){
            $oThis = self::CreateInstanceIfNotExists();

            $aP = array();
            $iOffset = 0;

            while(preg_match('/(\{\$(.*?)\})/i', $oThis->sBuffer, $aMatches, PREG_OFFSET_CAPTURE, $iOffset)){
                $mVar = $aMatches[2][0];

                if(Storage::Has($mVar)){
                    $mTo = Storage::Get($mVar);

                    if(is_bool($mTo))
                        $mTo = ($mTo) ? "true" : "false";

                    $mTo = html_entity_decode($mTo, ENT_NOQUOTES/*, Config::Read("l10n.charset")*/);
                    $oThis->sBuffer = str_replace($aMatches[0][0], $mTo, $oThis->sBuffer);
                }

                $iOffset = $aMatches[0][1]+strlen($aMatches[0][0]);
            }
        }
1124499
function replacePositionalVariables(command) {
  return command.replace(/\$(\d)/g, (match, number) => {
    return process.argv[number]
  })
}
621943
function findVariables(string) {
  // Do not parse empty files. Otherwise gonzales.parse will fail
  if (!string) {
    return [];
  }

  var out = [],
      ast = gonzales.parse(string, {
        syntax: 'less'
      });

  ast.traverseByType('value', function(subAst) {
    subAst.traverseByType('variable', function(node) {
      out.push(node.content.toString());
    });
  });

  return out;
}
425533
private boolean substitute(final String aKey) {
		boolean madeChange = false;

		if (substituting.contains(aKey)) {
			backing.put(aKey, "");
			booleanBacking.remove(aKey);
			recordMessage("WARNING: Recursive substitution detected on parameter " + aKey);
			String history = locations.get(aKey);
			locations.put(aKey, history + "recursion detected, using null value; " + history);
			return true;
		}

		try {
			substituting.add(aKey);

			String value = (String) backing.get(aKey);

			int start = findStartVariable(value);

			if (start == -1) {
				return madeChange;
			}

			int end = value.indexOf('}', start);

			if (end == -1) {
				return madeChange;
			}

			String variableName = value.substring(start + 2, end);

			madeChange = madeChange || substitute(variableName);

			String variableValue = get(variableName);

			if (variableValue == null) {
				return madeChange;
			}

			String newValue = value.substring(0, start) + variableValue + value.substring(end + 1);

			madeChange = true;

			backing.put(aKey, newValue);

			if ("yes".equals(newValue) || "true".equals(newValue)) {
				booleanBacking.add(aKey);
			} else {
				booleanBacking.remove(aKey);
			}

			// Record this substitution in the history
			String history = locations.get(aKey);
			history = "substitution of ${" + variableName + "}; " + history;
			locations.put(aKey, history);

			return madeChange;
		} finally {
			substituting.remove(aKey);
		}
	}
683357
function variableReplacementBuilder(v) {
        var pattern,
            name = v.name,
            from = v.from,
            to = v.to;

        if (util.isUndefined(to)) {
            grunt.log.error().error('"to" must be defined in a variable replacement instruction');
            return false;
        }

        if (util.isUndefined(name) && util.isUndefined(from)) {
            grunt.log.error().error('one of "name" or "from" must be defined in a variable replacement instruction');
            return false;
        }

        if (!util.isUndefined(name) && !util.isString(name) && !util.isRegex(name)) {
            grunt.log.error().error('"name" must be a string or a regex in a variable replacement instruction');
            return false;
        }

        if (!util.isUndefined(from) && !util.isString(from) && !util.isNumber(from) && !util.isBoolean(from)) {
            grunt.log.error().error('"from" must be a string, a number or a boolean in a variable replacement instruction');
            return false;
        }

        if (!util.isString(to) && !util.isNumber(to) && !util.isBoolean(to)) {
            grunt.log.error().error('"to" must be a string, a number or a boolean in a variable replacement instruction');
            return false;
        }

        pattern = buildVariableReplacementPattern(name, from, to);

        return {
            pattern: pattern,
            replacement: function (match, p1, p2, p3) {
                grunt.log
                    .debug('matching variable replacement'.bold)
                    .debug(('match=' + match).cyan)
                    .debug(('captured groups=' + grunt.log.wordlist([p1, p2, p3])).cyan);

                return p1 + to + p3;
            }
        };
    }
186480
def substitute_variables!(properties)
      # transform values and substitute for special values
      # https://stackoverflow.com/questions/34595142/process-nested-hash-to-convert-all-values-to-strings
      #
      # Examples:
      #   "{stack_name}.stag.boltops.com." => development-demo-web.stag.boltops.com.
      #   "{stack_name}.stag.boltops.com." => dev-demo-web-2.stag.boltops.com.
      properties.deep_merge(properties) do |_,_,v|
        if v.is_a?(String)
          v.sub!('{stack_name}', @stack_name) # unsure why need shebang, but it works
        else
          v
        end
      end
      properties
    end
1152305
def _get_replaced_code(self, names):
        
        code = self._code
        
        # Modify name
        fname = names[self]
        code = code.replace(" " + self.name + "(", " " + fname + "(")

        # Apply string replacements first -- these may contain $placeholders
        for key, val in self._replacements.items():
            code = code.replace(key, val)
        
        # Apply assignments to the end of the function
        
        # Collect post lines
        post_lines = []
        for key, val in self._assignments.items():
            if isinstance(key, Variable):
                key = names[key]
            if isinstance(val, ShaderObject):
                val = val.expression(names)
            line = '    %s = %s;' % (key, val)
            post_lines.append(line)
            
        # Add a default $post placeholder if needed
        if 'post' in self._expressions:
            post_lines.append('    $post')
            
        # Apply placeholders for hooks
        post_text = '\n'.join(post_lines)
        if post_text:
            post_text = '\n' + post_text + '\n'
        code = code.rpartition('}')
        code = code[0] + post_text + code[1] + code[2]

        # Add a default $pre placeholder if needed
        if 'pre' in self._expressions:
            m = re.search(fname + r'\s*\([^{]*\)\s*{', code)
            if m is None:
                raise RuntimeError("Cound not find beginning of function '%s'" 
                                   % fname) 
            ind = m.span()[1]
            code = code[:ind] + "\n    $pre\n" + code[ind:]
        
        # Apply template variables
        for key, val in self._expressions.items():
            val = val.expression(names)
            search = r'\$' + key + r'($|[^a-zA-Z0-9_])'
            code = re.sub(search, val+r'\1', code)

        # Done
        if '$' in code:
            v = parsing.find_template_variables(code)
            logger.warning('Unsubstituted placeholders in code: %s\n'
                           '  replacements made: %s', 
                           v, list(self._expressions.keys()))
        
        return code + '\n'
164436
function(command) {
        var patt = /("[^"]*")/,
            quotedStringPlaceholder = "__QUOTEDSTR__",
            escapedQuotePlaceholder = "__ESCAPED_QUOTE__",
            matches = [],
            match;

        command = command.replace(/\\\"/g, escapedQuotePlaceholder);

        while ((match = patt.exec(command))) {
            var matched = match[0];
            command =
                command.substr(0, match.index) + quotedStringPlaceholder + command.substr(match.index + matched.length);
            matches.push(matched.substring(1, matched.length - 1));
        }

        var parts = command.split(" ");
        parts = parts.map(function(part) {
            var item = part.trim();
            if (item === quotedStringPlaceholder) {
                item = matches.shift();
            }
            item = item.replace(new RegExp(escapedQuotePlaceholder, "g"), '"');
            return item;
        });

        return parts;
    }
1211336
def mixed_use_of_local_and_run(self):
        
        cxn = Connection("localhost")
        result = cxn.local("echo foo", hide=True)
        assert result.stdout == "foo\n"
        assert not cxn.is_connected  # meh way of proving it didn't use SSH yet
        result = cxn.run("echo foo", hide=True)
        assert cxn.is_connected  # NOW it's using SSH
        assert result.stdout == "foo\n"
1010062
function reformatCode(code) {
     var APPLY_LINE_NUMBERS = false;
     var lineNumberOffset = 0;
     var ENV = Espruino.Core.Env.getData();
     if (ENV && ENV.VERSION_MAJOR && ENV.VERSION_MINOR) {
       if (ENV.VERSION_MAJOR>1 ||
           ENV.VERSION_MINOR>=81.086) {
         if (Espruino.Config.STORE_LINE_NUMBERS)
           APPLY_LINE_NUMBERS = true;
       }
     }
    // Turn cr/lf into just lf (eg. windows -> unix)
    code = code.replace(/\r\n/g,"\n");
    // First off, try and fix funky characters
    for (var i=0;i<code.length;i++) {
      var ch = code.charCodeAt(i);
      if ((ch<32 || ch>255) && ch!=9/*Tab*/ && ch!=10/*LF*/ && ch!=13/*CR*/) {
        console.warn("Funky character code "+ch+" at position "+i+". Replacing with ?");
        code = code.substr(0,i)+"?"+code.substr(i+1);
      }
    }

    /* Search for lines added to the start of the code by the module handler.
    Ideally there would be a better way of doing this so line numbers stayed correct,
    but this hack works for now. Fixes EspruinoWebIDE#140 */
    if (APPLY_LINE_NUMBERS) {
      var l = code.split("\n");
      var i = 0;
      while (l[i] && (l[i].substr(0,8)=="Modules." ||
                      l[i].substr(0,8)=="setTime(")) i++;
      lineNumberOffset = -i;
    }

    var resultCode = "\x10"; // 0x10 = echo off for line
    /** we're looking for:
     *   `a = \n b`
     *   `for (.....) \n X`
     *   `if (.....) \n X`
     *   `if (.....) { } \n else foo`
     *   `while (.....) \n X`
     *   `do \n X`
     *   `function (.....) \n X`
     *   `function N(.....) \n X`
     *   `var a \n , b`    `var a = 0 \n, b`
     *   `var a, \n b`     `var a = 0, \n b`
     *   `a \n . b`
     *   `foo() \n . b`
     *   `try { } \n catch \n () \n {}`
     *
     *   These are divided into two groups - where there are brackets
     *   after the keyword (statementBeforeBrackets) and where there aren't
     *   (statement)
     *
     *   We fix them by replacing \n with what you get when you press
     *   Alt+Enter (Ctrl + LF). This tells Espruino that it's a newline
     *   but NOT to execute.
     */
    var lex = Espruino.Core.Utils.getLexer(code);
    var brackets = 0;
    var curlyBrackets = 0;
    var statementBeforeBrackets = false;
    var statement = false;
    var varDeclaration = false;
    var lastIdx = 0;
    var lastTok = {str:""};
    var tok = lex.next();
    while (tok!==undefined) {
      var previousString = code.substring(lastIdx, tok.startIdx);
      var tokenString = code.substring(tok.startIdx, tok.endIdx);
      //console.log("prev "+JSON.stringify(previousString)+"   next "+tokenString);

      /* Inserting Alt-Enter newline, which adds newline without trying
      to execute */
      if (brackets>0 || // we have brackets - sending the alt-enter special newline means Espruino doesn't have to do a search itself - faster.
          statement || // statement was before brackets - expecting something else
          statementBeforeBrackets ||  // we have an 'if'/etc
          varDeclaration || // variable declaration then newline
          tok.str=="," || // comma on newline - there was probably something before
          tok.str=="." || // dot on newline - there was probably something before
          tok.str=="=" || // equals on newline - there was probably something before
          tok.str=="else" || // else on newline
          lastTok.str=="else" || // else befgore newline
          tok.str=="catch" || // catch on newline - part of try..catch
          lastTok.str=="catch"
        ) {
        //console.log("Possible"+JSON.stringify(previousString));
        previousString = previousString.replace(/\n/g, "\x1B\x0A");
      }

      var previousBrackets = brackets;
      if (tok.str=="(" || tok.str=="{" || tok.str=="[") brackets++;
      if (tok.str=="{") curlyBrackets++;
      if (tok.str==")" || tok.str=="}" || tok.str=="]") brackets--;
      if (tok.str=="}") curlyBrackets--;

      if (brackets==0) {
        if (tok.str=="for" || tok.str=="if" || tok.str=="while" || tok.str=="function" || tok.str=="throw") {
          statementBeforeBrackets = true;
          varDeclaration = false;
        } else if (tok.str=="var") {
          varDeclaration = true;
        } else if (tok.type=="ID" && lastTok.str=="function") {
          statementBeforeBrackets = true;
        } else if (tok.str=="try" || tok.str=="catch") {
          statementBeforeBrackets = true;
        } else if (tok.str==")" && statementBeforeBrackets) {
          statementBeforeBrackets = false;
          statement = true;
        } else if (["=","^","&&","||","+","+=","-","-=","*","*=","/","/=","%","%=","&","&=","|","|="].indexOf(tok.str)>=0) {
          statement = true;
        } else {
          if (tok.str==";") varDeclaration = false;
          statement = false;
          statementBeforeBrackets = false;
        }
      }
      /* If we're at root scope and had whitespace/comments between code,
      remove it all and replace it with a single newline and a
      0x10 (echo off for line) character. However DON'T do this if we had
      an alt-enter in the line, as it was there to stop us executing
      prematurely */
      if (previousBrackets==0 &&
          previousString.indexOf("\n")>=0 &&
          previousString.indexOf("\x1B\x0A")<0) {
        previousString = "\n\x10";
        // Apply line numbers to each new line sent, to aid debugger
        if (APPLY_LINE_NUMBERS && tok.lineNumber && (tok.lineNumber+lineNumberOffset)>0) {
          // Esc [ 1234 d
          // This is the 'set line number' command that we're abusing :)
          previousString += "\x1B\x5B"+(tok.lineNumber+lineNumberOffset)+"d";
        }
      }

      // add our stuff back together
      resultCode += previousString+tokenString;
      // next
      lastIdx = tok.endIdx;
      lastTok = tok;
      tok = lex.next();
    }
    //console.log(resultCode);
    if (brackets>0) {
      Espruino.Core.Notifications.error("You have more open brackets than close brackets. Please see the hints in the Editor window.");
      return undefined;
    }
    if (brackets<0) {
      Espruino.Core.Notifications.error("You have more close brackets than open brackets. Please see the hints in the Editor window.");
      return undefined;
    }
    return resultCode;
  }
675583
private function extractPlaceholders(): void
  {
    $unknown = [];

    preg_match_all('(@[A-Za-z0-9\_\.]+(\%type)?@)', $this->routineSourceCode, $matches);
    if (!empty($matches[0]))
    {
      foreach ($matches[0] as $placeholder)
      {
        if (isset($this->replacePairs[strtoupper($placeholder)]))
        {
          $this->replace[$placeholder] = $this->replacePairs[strtoupper($placeholder)];
        }
        else
        {
          $unknown[] = $placeholder;
        }
      }
    }

    $this->logUnknownPlaceholders($unknown);
  }
330281
def obfuscate_variable(
        tokens,
        index,
        replace,
        replacement,
        right_of_equal,
        inside_parens,
        inside_function):
    
    def return_replacement(replacement):
        VAR_REPLACEMENTS[replacement] = replace
        return replacement
    tok = tokens[index]
    token_type = tok[0]
    token_string = tok[1]
    if index > 0:
        prev_tok = tokens[index-1]
    else: # Pretend it's a newline (for simplicity)
        prev_tok = (54, '\n', (1, 1), (1, 2), '#\n')
    prev_tok_string = prev_tok[1]
    try:
        next_tok = tokens[index+1]
    except IndexError: # Pretend it's a newline
        next_tok = (54, '\n', (1, 1), (1, 2), '#\n')
    if token_string == "import":
        return '__skipline__'
    if next_tok[1] == '.':
        if token_string in imported_modules:
            return None
    if token_string == "=":
        return '__right_of_equal__'
    if token_string == "(":
        return '__open_paren__'
    if token_string == ")":
        return '__close_paren__'
    if token_string == ",":
        return '__comma__'
    if token_type != tokenize.NAME:
        return None # Skip this token
    if token_string.startswith('__'):
        return None
    if prev_tok_string == 'def':
        return '__skipnext__' # Don't want to touch functions
    if token_string == replace and prev_tok_string != '.':
        if inside_function:
            if token_string not in keyword_args[inside_function]:
                if not right_of_equal:
                    if not inside_parens:
                        return return_replacement(replacement)
                    else:
                        if next_tok[1] != '=':
                            return return_replacement(replacement)
                elif not inside_parens:
                    return return_replacement(replacement)
                else:
                    if next_tok[1] != '=':
                        return return_replacement(replacement)
        elif not right_of_equal:
            if not inside_parens:
                return return_replacement(replacement)
            else:
                if next_tok[1] != '=':
                    return return_replacement(replacement)
        elif right_of_equal and not inside_parens:
            return return_replacement(replacement)