Replace a repo entry in filepath with repostr
502044
def _mod_repo_in_file(repo, repostr, filepath):
    '''
    
    '''
    with salt.utils.files.fopen(filepath) as fhandle:
        output = []
        for line in fhandle:
            cols = salt.utils.args.shlex_split(
                salt.utils.stringutils.to_unicode(line).strip()
            )
            if repo not in cols:
                output.append(line)
            else:
                output.append(salt.utils.stringutils.to_str(repostr + '\n'))
    with salt.utils.files.fopen(filepath, 'w') as fhandle:
        fhandle.writelines(output)
1076418
def addFile(self, path, msg=""):
        """"""
        item = Item.from_path(repo=self.repo, path=path)
        self.addItem(item)
1077072
def update_repo(repo_dir, repo_url, fetch=False):
    """"""
    repo_exists = os.path.exists(repo_dir)
    if not repo_exists:
        log.info("Cloning repo {}".format(repo_url))
        repo = repo_clone(repo_dir, repo_url)

    # Make sure the repo is properly prepared
    # and has all the refs required
    log.info("Fetching repo {} (fetch: {})".format(repo_url, fetch))
    repo = repo_pull(repo_dir, repo_url, fetch)

    return repo
1268532
function reparsePath(oldpath) {
        if (oldpath.indexOf("?") >= 0) {
            var vars = oldpath.split("?")[1].split("&");
            var result = oldpath.split("?")[0] + '?';
            var firstFlag = 0;
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (ignoredParams.search(pair[0]) < 0) {
                    if (firstFlag === 0) {
                        result = result + pair[0] + '=' + pair[1];
                        firstFlag = 1;
                    }
                    else {
                        result = result + '&' + pair[0] + '=' + pair[1];
                    }
                }
            }
            return result;
        }
        else {
            return oldpath;
        }
    }
1029974
def require_repo(directory=None):
    """"""
    if directory and not os.path.isdir(directory):
        raise ValueError('Directory not found: ' + repr(directory))
    repo = repo_path(directory)
    if not os.path.isdir(repo):
        raise RepositoryNotFoundError(directory)
    return repo
874242
function repoFiles (options, callback) {
  var url = options.url
  var files = options.files

  if (!url || !files) {
    return callback(new Error('must specify url, files'))
  }

  var data = []

  async.forEachOf(files, function (item, key, callback) {
    request({
      url: url + item.name
    }, function (err, json) {
      if (err) return callback(err)

      if (json && json.type && json.type === 'FeatureCollection') {
        json.name = item.name
        json.sha = item.sha
        data.push(json)

        return callback(null)
      }

      callback(new Error('problem accessing file ' + url + '/' + key))
    })
  }, function (err) {
    if (err) return callback(err)
    callback(null, data)
  })
}
429103
function parseGitUrl(giturl) {
    var ref, uri, fileParts, filepath;

    if (!checkGitUrl(giturl)) return null;
    giturl = giturl.slice(GIT_PREFIX.length);

    uri = new URI(giturl);
    ref = uri.fragment() || 'master';
    uri.fragment(null);

    // Extract file inside the repo (after the .git)
    fileParts =uri.path().split('.git');
    filepath = fileParts.length > 1? fileParts.slice(1).join('.git') : '';
    if (filepath[0] == '/') filepath = filepath.slice(1);

    // Recreate pathname without the real filename
    uri.path(_.first(fileParts)+'.git');

    return {
        host: uri.toString(),
        ref: ref || 'master',
        filepath: filepath
    };
}
406433
function getFileUrl (repo, path, sha, line) {
  var url = "https://github.com/" + repo + "/blob/";

  if (sha) {
    url += sha + "/";
  }

  url += path;

  if (line) {
    url += "#L" + line;
  }

  return url;
}
1120546
function updateIosPlist (targetFilePath, configItems) {
        var infoPlist = plist.parse(fs.readFileSync(targetFilePath, 'utf-8')),
            tempInfoPlist;

        _.each(configItems, function (item) {
            var key = item.parent;
            var plistXml = '<plist><dict><key>' + key + '</key>';
            plistXml += eltreeToXmlString(item.data) + '</dict></plist>';

            var configPlistObj = plist.parse(plistXml);
            infoPlist[key] = configPlistObj[key];
            logger.verbose("Write to plist; key="+key+"; value="+tostr(configPlistObj[key]));
        });

        tempInfoPlist = plist.build(infoPlist);
        tempInfoPlist = tempInfoPlist.replace(/<string>[\s\r\n]*<\/string>/g,'<string></string>');
        fs.writeFileSync(targetFilePath, tempInfoPlist, 'utf-8');
    }
1342553
def replace_baseline_repr(self, linenum, update):
        
        # use property to access lines to read them from file if necessary
        lines = self.lines

        count = 0
        delimiter = None
        for index in range(linenum - 1, -1, -1):
            line = lines[index]
            if delimiter is None:
                single_quote_index = line.rfind("'''")
                double_quote_index = line.rfind('"""')
                if double_quote_index >= 0:
                    if double_quote_index > single_quote_index:
                        delimiter = '"""'
                    else:
                        delimiter = "'''"
                elif single_quote_index >= 0:
                    delimiter = "'''"
                else:
                    continue
            count += lines[index].count(delimiter)
            if count >= 2:
                linenum = index
                break
        else:
            docstr_not_found = (
                '{}:{}: could not find baseline docstring'
                ''.format(self.showpath(self.path), linenum))
            raise RuntimeError(docstr_not_found)

        old_content = '\n'.join(lines[linenum:])

        match = self.REGEX.match(old_content)

        if match is None:
            docstr_not_found = (
                '{}:{}: could not find docstring'.format(self.path, linenum))
            raise RuntimeError(docstr_not_found)

        new_content = match.group('prefix') + update + match.group('suffix')

        lines[linenum:] = new_content.split('\n')
1300819
def replace_version_tag(self):
        """"""
        version_tag = self.arguments.get('<version>')
        special_keywords = ['current', 'latest']
        if version_tag in special_keywords:
            logger.error("releasing version '{}' is disallowed. Did you mean 'version upload'?".format(version_tag))
            raise SystemExit(1)
        placeholders = dict(major=0, minor=1, trivial=2)
        placeholder = placeholders.get(version_tag)
        if placeholder is None:
            return version_tag
        current_version = self.get_git_describe().lstrip('v')
        version_numbers = current_version.split('-')[0].split('.')
        version_numbers = [int(item) for item in version_numbers]
        version_numbers = version_numbers[:placeholder + 1]
        while len(version_numbers) < 3:
            version_numbers.append(0)
        version_numbers[placeholder] += 1
        return '.'.join([str(item) for item in version_numbers[:2 if placeholder < 2 else 3]])
492708
async function archiveGitTree(repPath, tree, archive) {
  // recursively collect all entries (blobs and trees)
  const allEntries = await collectTreeEntries(repPath, tree, [], '');

  const process = async ({ type, oid, path }) => {
    if (type === 'tree' || type === 'commit') {
      // directory or submodule
      archive.append(null, { name: `${path}/` });
    } else {
      // blob
      const stream = await createBlobReadStream(repPath, oid);
      archive.append(stream, { name: path });
    }
  };

  return new Promise((resolve, reject) => {
    async.eachSeries(
      allEntries,
      async.asyncify(process),
      (err) => {
        if (err) {
          reject(err);
        } else {
          resolve(archive);
        }
      },
    );
  });
}
1037365
def get_repo_content(path):
    
    path = Path(path)

    if zipfile.is_zipfile(str(path)):
        with zipfile.ZipFile(str(path)) as zz:
            filelist = [info.filename for info in zz.infolist()]
        iszip = True
    else:
        iszip = False
        filelist = [str(f) for f in path.glob('**/*') if f.is_file()]
    return namedtuple('repocontent', ['iszip', 'filelist'])(iszip, filelist)
515636
def replace_git_url(generator):
    """"""
    template = g_jinja2.get_template(GIT_TEMPLATE)

    should_cache = generator.context.get('GIT_CACHE_ENABLED')
    cache_location = generator.context.get('GIT_CACHE_LOCATION')

    for article in generator.articles:
        for match in git_regex.findall(article._content):
            params = collections.defaultdict(str)
            repo = match[1]
            filename = match[3]
            branch = match[5]
            hash = match[7]

            params['repo'] = match[1]
            params['filename'] = match[3]
            if match[5]:
                params['branch'] = match[5]
            if match[7]:
                params['hash'] = match[7]

            logger.info('[git]: Found repo {}, filename {}, branch {} and hash {}'.format(repo, filename, branch, hash))
            logger.info('[git]: {}'.format(params))

            body = None if not should_cache else get_cache(cache_location, **params)

            # Fetch the git
            if not body:
                logger.info('[git]: Git did not exist in cache, fetching...')
                response = fetch_git(**params)
                body = get_body(response)

                if should_cache:
                    logger.info('[git]: Saving git to cache...')
                    cache_params = copy.copy(params)
                    cache_params['body'] = body
                    set_cache(cache_location, **cache_params)
            else:
                logger.info('[git]: Found git in cache.')

            # Create a context to render with
            context = generator.context.copy()
            context.update({
                'code': body,
                'footer': 'full',
                'base': __url__,
                'filename': filename,
                'url': git_url(**params)
            })
            replacement = template.render(context)
            article._content = article._content.replace(match[0], replacement)
410727
def replace_all(filepath, searchExp, replaceExp):
    
    for line in fileinput.input(filepath, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp, replaceExp)
        sys.stdout.write(line)
514812
def clone(cls, srcpath, destpath):
        """"""
        try:
            os.makedirs(destpath)
        except OSError as e:
            if not e.errno == errno.EEXIST:
                raise
        cmd = [SVNADMIN, 'dump', '--quiet', '.']
        dump = subprocess.Popen(
               cmd, cwd=srcpath, stdout=subprocess.PIPE,
               stderr=subprocess.PIPE,
        )
        repo = cls.create(destpath)
        repo.load(dump.stdout)
        stderr = dump.stderr.read()
        dump.stdout.close()
        dump.stderr.close()
        dump.wait()
        if dump.returncode != 0:
            raise subprocess.CalledProcessError(dump.returncode, cmd, stderr)
        return repo
843438
def reparse(self, filepath):
        """"""
        #The easiest way to do this is to touch the file and then call
        #the regular parse method so that the cache becomes invalidated.
        self.tramp.touch(filepath)
        self.parse(filepath)