Changes https:// in .git/config files to git@ and makes
    appropriate changes to colons and slashses
177995
def permit_gitrepo(config_fpath, writeback=False):
    
    # Define search replace patterns
    username_regex = utool.named_field('username', utool.REGEX_VARNAME)
    username_repl = utool.backref_field('username')
    regexpat = r'https://github.com/' + username_regex + '/'
    replpat = r'git@github.com:' + username_repl + '/'
    # Read and replace
    lines = utool.read_from(config_fpath, aslines=True)
    newlines = utool.regex_replace_lines(lines, regexpat, replpat)
    # Writeback or print
    if not WRITEBACK:
        print(''.join(newlines))
    else:
        utool.write_to(config_fpath, newlines, aslines=True)
426732
def normalize!
      if path && path == ''
        set_path('/')
      end
      if host && host != host.downcase
        set_host(self.host.downcase)
      end        
    end
1340026
def _make_git(config_info):
    """"""
    git_args = {}

    def _add_value(value, key):
        args_key, args_value = _GIT_ARG_FNS[key](value)
        git_args[args_key] = args_value

    devpipeline_core.toolsupport.args_builder("git", config_info, _GIT_ARGS, _add_value)
    if git_args.get("uri"):
        return devpipeline_scm.make_simple_scm(Git(git_args), config_info)
    else:
        raise Exception("No git uri ({})".format(config_info.config.name))
905559
def _fix_repo_url(repo_url):
    """"""
    parsed = urlparse.urlparse(repo_url)
    
    if parsed.scheme not in ('http', 'https'):
        # Fix only for http and https.
        return repo_url

    username = parsed.username or ""
    password = parsed.password or ""
    port = ":" + parsed.port if parsed.port else ""
    netloc = "".join((username, ":", password, "@", parsed.hostname, port))
    part_list = list(parsed)
    part_list[1] = netloc
    return urlparse.urlunparse(part_list)
1185908
def add(path, msg = "", options = {})
      exit_status = 0
      dir  = File.realpath(File.dirname(path))
      root = rootdir(path)
      relative_path_to_root = Pathname.new( File.realpath(path) ).relative_path_from Pathname.new(root)
      real_msg = ((msg.empty?) ? "add '#{relative_path_to_root}'" : msg)
      opts = '-f' if options[:force]
      Dir.chdir( dir ) do
        exit_status = run %(
                  git add #{opts} #{path}
                  git commit -s -m "#{real_msg}" #{path}
                )
      end
      exit_status.to_i
    end
234412
def wrap_name_from_git(prefix, suffix, *args, **kwargs):
    
    # 64 is maximum length allowed by OpenShift
    # 2 is the number of dashes that will be added
    prefix = ''.join(filter(VALID_BUILD_CONFIG_NAME_CHARS.match, list(prefix)))
    suffix = ''.join(filter(VALID_BUILD_CONFIG_NAME_CHARS.match, list(suffix)))
    kwargs['limit'] = kwargs.get('limit', 64) - len(prefix) - len(suffix) - 2
    name_from_git = make_name_from_git(*args, **kwargs)
    return '-'.join([prefix, name_from_git, suffix])
582894
def repo_url_to_project_name(url, normalize=True):
    # type: (str, bool) -> str
    
    if url.startswith('http'):
        http_url = urlparse(url)
        name = http_url.path.replace('.git', '').lstrip('/').strip()
    else:
        name = url[url.index(':') + 1:].replace('.git', '').strip()
    if normalize:
        return name.replace('/', ' / ').title()
    return name
61132
function gitPush () {
      var branch = options.branch;
      var withForce = options.force ? ' --force ' : '';

      if (options.remoteBranch) branch += ':' + options.remoteBranch;

      log.subhead('Pushing ' + options.branch + ' to ' + options.remote + withForce);
      execWrap('git push ' + withForce + remoteName + ' ' + branch, false, true);

      if (options.tag) {
        execWrap('git push ' + remoteName + ' ' + options.tag);
      }
    }
888447
def modified_files(options)
      flags = '--cached' if options[:staged]
      refs = options[:refs]
      subcmd = options[:subcmd] || 'diff'

      `git #{subcmd} --name-only -z --diff-filter=ACMR --ignore-submodules=all #{flags} #{refs}`.
        split("\0").
        map(&:strip).
        reject(&:empty?).
        map { |relative_file| File.expand_path(relative_file) }
    end
332309
def native(cmd, opts = [], chdir = true, redirect = '', &block)
      validate

      ENV['GIT_DIR'] = @git_dir
      ENV['GIT_INDEX_FILE'] = @git_index_file
      ENV['GIT_WORK_TREE'] = @git_work_dir
      path = @git_work_dir || @git_dir || @path

      opts = [opts].flatten.map {|s| escape(s) }.join(' ')
      git_cmd = "git #{cmd} #{opts} #{redirect} 2>&1"

      out = nil
      if chdir && (Dir.getwd != path)
        Dir.chdir(path) { out = run_command(git_cmd, &block) }
      else
        out = run_command(git_cmd, &block)
      end

      if @logger
        @logger.info(git_cmd)
        @logger.debug(out)
      end

      if $?.exitstatus > 0
        if $?.exitstatus == 1 && out == ''
          return ''
        end
        raise Git::CommandFailed.new(git_cmd, $?.exitstatus, out.to_s)
      end
      out
    end
897186
function replacer(match, quote, require) {
        var replacement = 'require(' + quote;
        try {
            resolve.sync(require);
        } catch (exc) {
            try {
                // Try to resolve the require statement starting from the root folder
                resolve.sync(require, {paths: ['.']});
                replacement += relativeToRoot + path.sep;
            } catch (exc2) {
            }
        }
        replacement += require + quote + ')';
//        console.log(replacement);
        return replacement;
    }
1358888
private void gitSetConfig(final String name, String value)
            throws MojoFailureException, CommandLineException {
        if (value == null || value.isEmpty()) {
            value = "\"\"";
        }

        // ignore error exit codes
        executeGitCommandExitCode("config", name, value);
    }
970913
def git_url_ssh_to_https(url):
    
    path = url.split('github.com', 1)[1][1:].strip()
    new = 'https://{GITHUB_TOKEN}@github.com/%s' % path
    print('rewriting git url to: %s' % new)
    return new.format(GITHUB_TOKEN=os.getenv('GITHUB_TOKEN'))
371008
function (src, type, line) {
		    var pack;
		    if( pack  = config.pageConfig.project ){
		        return pack.source +
		            // removes can/ because that is not part of
		            // the url and that identifier comes from the base .github url
		            src.replace(/^\w+\/|^\.\//,"/") +
		            (type !== 'page' && type !== 'constructor' && line ? '#L' + line : '');


		    } else {
		        return ""
		    }

		}
1243267
function applyPatch (oldStr, uniDiff) {
  var diffstr = uniDiff.split('\n');
  var diff = [];
  var remEOFNL = false,
      addEOFNL = false;

  // i = 4 in order to skip diff headers.
  for (var i = 4; i < diffstr.length; i++) {
    if(diffstr[i][0] === '@') {
      var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
      diff.unshift({
        start:meh[3],
        oldlength:meh[2],
        oldlines:[],
        newlength:meh[4],
        newlines:[]
      });
    } else if(diffstr[i][0] === '+') {
      diff[0].newlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === '-') {
      diff[0].oldlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === ' ') {
      diff[0].newlines.push(diffstr[i].substr(1));
      diff[0].oldlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === '\\') {
      if (diffstr[i-1][0] === '+') {
        remEOFNL = true;
      } else if(diffstr[i-1][0] === '-') {
        addEOFNL = true;
      }
    }
  }

  var str = oldStr.split('\n');
  for (i = diff.length - 1; i >= 0; i--) {
    var d = diff[i];
    for (var j = 0; j < d.oldlength; j++) {
      if(str[d.start-1+j] !== d.oldlines[j]) {
        return false;
      }
    }
    Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
  }

  if (remEOFNL) {
    while (!str[str.length-1]) {
      str.pop();
    }
  } else if (addEOFNL) {
    str.push('');
  }
  return str.join('\n');
}
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)
1305038
def git_permalink(content, git_content):
    '''
    
    '''
    if not content.settings['GIT_GENERATE_PERMALINK']:
        return

    if not string_to_bool(content.metadata.get('git_permalink', 'yes')):
        # Disable for this content
        return

    if not git_content.is_committed():
        return

    permalink_hash = hashlib.sha1()
    update_hash_from_str(permalink_hash, git_content.get_oldest_commit())
    update_hash_from_str(permalink_hash, git_content.get_oldest_filename())
    git_permalink_id_raw = base64.urlsafe_b64encode(permalink_hash.digest())
    git_permalink_id = git_permalink_id_raw.decode("UTF-8")
    permalink_id_metadata_key = content.settings['PERMALINK_ID_METADATA_KEY']

    if permalink_id_metadata_key in content.metadata:
        content.metadata[permalink_id_metadata_key] = (
            ','.join((
                content.metadata[permalink_id_metadata_key], git_permalink_id))
        )
    else:
        content.metadata[permalink_id_metadata_key] = git_permalink_id