Compatibility layer for gitbook < 2.5.0
498477
function(cfg) {
            var sharingLink = _.get(cfg, 'links.sharing', {});
            cfg.pluginsConfig.sharing = _.defaults(cfg.pluginsConfig.sharing || {}, {});

            _.each(sharingLink, function(enabled, type) {
                if (enabled != false) return;

                if (type == 'all') cfg.pluginsConfig.sharing[type] = [];
                else cfg.pluginsConfig.sharing[type] = false;
            });

            return cfg;
        }
932603
function resolveForVersion(version, platformID, opts) {
    opts = _.defaults(opts || {}, {
        // Order for filetype
        filePreference: ['.exe', '.dmg', '.deb', '.rpm', '.tgz', '.tar.gz', '.zip', '.nupkg'],
        wanted: null
    });

    // Prepare file prefs
    if (opts.wanted) opts.filePreference = _.uniq([opts.wanted].concat(opts.filePreference));

    // Normalize platform id
    platformID = detectPlatform(platformID);

    return _.chain(version.platforms)
        .filter(function(pl) {
            return pl.type.indexOf(platformID) === 0;
        })
        .sort(function(p1, p2) {
            var result = 0;

            // Compare by arhcitecture ("osx_64" > "osx")
            if (p1.type.length > p2.type.length) result = -1;
            else if (p2.type.length > p1.type.length) result = 1;

            // Order by file type if samee architecture
            if (result == 0) {
                var ext1 = path.extname(p1.filename);
                var ext2 = path.extname(p2.filename);
                var pos1 = _.indexOf(opts.filePreference, ext1);
                var pos2 = _.indexOf(opts.filePreference, ext2);

                pos1 = pos1 == -1? opts.filePreference.length : pos1;
                pos2 = pos2 == -1? opts.filePreference.length : pos2;

                if (pos1 < pos2) result = -1;
                else if (pos2 < pos1) result = 1;
            }
            return result;
        })
        .first()
        .value()
}
600800
def check_for_cygwin_mismatch():
    """"""
    if sys.platform in ('cygwin', 'win32'):  # pragma: no cover (windows)
        is_cygwin_python = sys.platform == 'cygwin'
        toplevel = cmd_output('git', 'rev-parse', '--show-toplevel')[1]
        is_cygwin_git = toplevel.startswith('/')

        if is_cygwin_python ^ is_cygwin_git:
            exe_type = {True: '(cygwin)', False: '(windows)'}
            logger.warn(
                'pre-commit has detected a mix of cygwin python / git\n'
                'This combination is not supported, it is likely you will '
                'receive an error later in the program.\n'
                'Make sure to use cygwin git+python while using cygwin\n'
                'These can be installed through the cygwin installer.\n'
                ' - python {}\n'
                ' - git {}\n'.format(
                    exe_type[is_cygwin_python], exe_type[is_cygwin_git],
                ),
            )
23550
function(hook, rules) {
			if (cfg.AVAILABLE_HOOKS.indexOf(hook) < 0 && !this.ignore) {
				this.error('hook "' + hook + '" not support');
			}

			if (!hooks[hook]) {
				hooks[hook] = new Githook(rules);
			}
			return hooks[hook];
		}
723353
def install(
        config_file, store,
        overwrite=False, hooks=False, hook_type='pre-commit',
        skip_on_missing_conf=False,
):
    """"""
    if cmd_output('git', 'config', 'core.hooksPath', retcode=None)[1].strip():
        logger.error(
            'Cowardly refusing to install hooks with `core.hooksPath` set.\n'
            'hint: `git config --unset-all core.hooksPath`',
        )
        return 1

    hook_path, legacy_path = _hook_paths(hook_type)

    mkdirp(os.path.dirname(hook_path))

    # If we have an existing hook, move it to pre-commit.legacy
    if os.path.lexists(hook_path) and not is_our_script(hook_path):
        shutil.move(hook_path, legacy_path)

    # If we specify overwrite, we simply delete the legacy file
    if overwrite and os.path.exists(legacy_path):
        os.remove(legacy_path)
    elif os.path.exists(legacy_path):
        output.write_line(
            'Running in migration mode with existing hooks at {}\n'
            'Use -f to use only pre-commit.'.format(legacy_path),
        )

    params = {
        'CONFIG': config_file,
        'HOOK_TYPE': hook_type,
        'INSTALL_PYTHON': sys.executable,
        'SKIP_ON_MISSING_CONFIG': skip_on_missing_conf,
    }

    with io.open(hook_path, 'w') as hook_file:
        contents = resource_text('hook-tmpl')
        before, rest = contents.split(TEMPLATE_START)
        to_template, after = rest.split(TEMPLATE_END)

        before = before.replace('#!/usr/bin/env python3', shebang())

        hook_file.write(before + TEMPLATE_START)
        for line in to_template.splitlines():
            var = line.split()[0]
            hook_file.write('{} = {!r}\n'.format(var, params[var]))
        hook_file.write(TEMPLATE_END + after)
    make_executable(hook_path)

    output.write_line('pre-commit installed at {}'.format(hook_path))

    # If they requested we install all of the hooks, do so.
    if hooks:
        install_hooks(config_file, store)

    return 0
957490
function createRelease(version) {
      if(version) {
        releaseOptions.target_commitish = version;
      }
      github.repos.createRelease(releaseOptions, function() {
        nextRepo();
      });
    }
636472
def rsync_git(local_path, remote_path, exclude=None, extra_opts=None,
              version_file='version.txt'):
    """"""
    with settings(hide('output', 'running'), warn_only=True):
        print(green('Version On Server: ' + run('cat ' + '{}/{}'.format(
              remote_path, version_file)).strip()))
    print(green('Now Deploying Version ' +
          write_version(join(local_path, version_file))))
    rsync(local_path, remote_path, exclude, extra_opts)
108320
async function commitVersionBump (version) {
  const gitDir = path.resolve(__dirname, '..')
  const gitArgs = ['commit', '-a', '-m', `Bump v${version}`, '-n']
  await GitProcess.exec(gitArgs, gitDir)
}
1331127
private void enforceVersionSupported()
    {
        if ( _versionSupported != null )
        {
            int majorSupported = _versionSupported.major();
            int minorSupported = _versionSupported.minor();

            if ( majorSupported < 0 )    // no real version support requirement
                return;

            AptControlInterface ci = getControlInterface();
            if ( ci == null )
                return;

            int majorPresent = -1;
            int minorPresent = -1;
            Version ciVersion = ci.getVersion();
            if ( ciVersion != null )
            {
                majorPresent = ciVersion.major();
                minorPresent = ciVersion.minor();

                if ( majorSupported >= majorPresent &&
                     (minorSupported < 0 || minorSupported >= minorPresent) )
                {
                    // Version requirement is satisfied
                    return;
                }
            }

            //
            // Version requirement failed
            //

            _ap.printError( _implDecl, "versionsupported.failed", _implDecl.getSimpleName(), majorSupported, minorSupported,
                            majorPresent, minorPresent );
        }
    }
348492
def _git_receive_v2(msg, tmpl):
    ''' 
    '''
    repo = _get_project(msg['msg'], key='repo')
    user = msg['msg']['agent']
    n_commits = msg['msg']['total_commits']
    commit_lbl = 'commit' if str(n_commits) == '1' else 'commits'
    branch = msg['msg']['branch']
    if 'refs/heads/' in branch:
        branch = branch.replace('refs/heads/', '')
    return tmpl.format(user=user, repo=repo,
                       branch=branch, n_commits=n_commits,
                       commit_lbl=commit_lbl)
770043
def release(
    ctx,
    bump,
    bump_type,
    commit_flag,
    message,
    tag_flag,
    confirm_flag,
    changelog_file,
    files,
    label_pattern,
    label_position,
    tag_pattern,
    current_version,
    stage,
    merge_pre,
    current_tag=None,
    versions=None,
):

    
    # If there isn't a current version, assume version 0.0.0
    current_version = current_version or Version()

    git = Git()
    from_tag = current_tag.name if current_tag else None

    # Delimiter of the block to be removed from the changelog file
    remove_pre_chglog = None

    # Look for the last final release version if the user want it
    if merge_pre and current_version.stage != "final":
        remove_pre_chglog = [current_version.string]

        for version in versions:
            if version.stage == "final":
                from_tag = version.tag.name
                remove_pre_chglog.append(version.string)
                break

    commit_list = git.log(_from=from_tag)

    msg(f'{label("Current version")} {current_version}')
    msg(f'{label("Commits found")} {len(commit_list)} since last release')

    if not commit_list:
        click.echo(" › Nothing to release.")
        ctx.exit()

    semantic_commits = commit_analyzer(commit_list, label_pattern, label_position)

    release_data = ReleaseDataTree(semantic_commits)

    bump_version_to = None

    # --bump, --major, --minor, --patch or commit message based version
    # are taken into account only if the current version is in final stage.
    if current_version.stage == "final":

        # --bump have precedence over any of --major, --minor or --patch
        bump_version_to = bump.string if bump else bump_type

        # Any manual bump have precedence over commit message based versions.
        bump_version_to = bump_version_to or release_data.bump_version_to

    try:
        new_version = get_next_version(current_version, bump_version_to, stage)
    except ValueError as e:
        ctx.fail(e)

    if not new_version:
        msg("The release of a lower versions is not supported for now.")
        ctx.abort()

    new_tag_name = tag_pattern.format(version=new_version.string)

    msg(f'{label("New version")} {new_version}')
    msg(f'{label("Changelog file")} {changelog_file.name}')

    # Messages about what tasks will be performed
    msg("Braulio will perform the next tasks :")
    msg(f"        Update {len(files) + 1} files.", prefix="")
    msg("        Add a release commit.", prefix="", silence=not commit_flag)
    msg(
        f"        Tag the repository with {new_tag_name}",
        prefix="",
        silence=not tag_flag,
    )

    msg("", prefix="")  # Print just a new line

    if confirm_flag or click.confirm(f"{prefix_mark}Continue?"):

        msg("Update changelog ", nl=False)

        update_chglog(
            changelog_file,
            new_version=new_version,
            current_version=current_version,
            release_data=release_data,
            remove=remove_pre_chglog,
        )

        msg(check_mark, prefix="")

        try:
            update_files(files, str(current_version), str(new_version))
        except ValueError as e:
            click.echo(e)
            ctx.abort()

        if commit_flag:
            message_args = {"new_version": new_version.string}

            if "{current_version}" in message:
                message_args["current_version"] = current_version.string

            commit_message = message.format(**message_args)

            msg(f"Add commit: {commit_message}", nl=False)

            files = [str(changelog_file)] + list(files)
            git.commit(commit_message, files=files)
            msg(f" {check_mark}", prefix="")

        if tag_flag:
            msg(f"Add tag {new_tag_name}", nl=False)
            git.tag(new_tag_name)
            msg(f" {check_mark}", prefix="")

        if "current_version" in ctx.obj.cfg_file_options:
            update_config_file("current_version", new_version.string)

        msg(f"Version {new_version} released successfully", suffix=" 🎉")
1212067
def install(force=False):
    """"""
    ret, git_dir, _ = run("git rev-parse --show-toplevel")
    if ret != 0:
        click.echo(
            "ERROR: Please run from within a GIT repository.",
            file=sys.stderr)
        raise click.Abort
    git_dir = git_dir[0]

    hooks_dir = os.path.join(git_dir, HOOK_PATH)

    for hook in HOOKS:
        hook_path = os.path.join(hooks_dir, hook)
        if os.path.exists(hook_path):
            if not force:
                click.echo(
                    "Hook already exists. Skipping {0}".format(hook_path),
                    file=sys.stderr)
                continue
            else:
                os.unlink(hook_path)

        source = os.path.join(sys.prefix, "bin", "kwalitee-" + hook)
        os.symlink(os.path.normpath(source), hook_path)
    return True
1035423
function gitVersionInfo(baseVer = '0.1.0') {
  const current = new Semver(baseVer);
  const identifier = current.prerelease[0] || 'beta';
  const prompt = [];
  const types = {
    major: 'major',
    minor: 'minor',
    patch: 'patch',
    premajor: 'pre-release major',
    preminor: 'pre-release minor',
    prepatch: 'pre-relase patch',
    prerelease: 'pre-release'
  };

  Object.keys(types).forEach(releaseType => {
    const newVer = Semver.inc(current.version, releaseType, releaseType.startsWith('pre') ? identifier : '');

    prompt.push({
      value: newVer,
      name: `${types[releaseType]} (${newVer})`
    });
  });

  return {
    current: current.version,
    prompt
  };
}
117599
function calculateVersion(officialRelease, callback) {
    var version = require('./package.json').version;

    if (officialRelease) {
        callback(version);
    } else {
        git.short(function (str) {
            callback(version + '+' + str);
        });
    }
}
696794
def clone(self):
        
        logger.debug("Attempting to clone {0}".format(self.book_repo_name))

        if self.path_exists():
            return False, "Error: Local clone of {0} already exists".format(self.book_repo_name)

        try:
            self.local_repo = git.Repo.clone_from(self.get_clone_url_ssh(), self.library_book_dir())
            return True, "Success! Cloned {0}".format(self.book_repo_name)
        except git.exc.GitCommandError as e:
            print(e)
            logger.debug("clone ran into an issue, likely remote doesn't exist")
            return False, "Error git returned  a fail code"
736682
def run(version, quiet, no_fetch, push, **kwargs):  # pragma: no cover
    
    if version:
        if NO_DISTRIBUTE:
            print(colored('Please install \'git-up\' via pip in order to '
                          'get version information.', 'yellow'))
        else:
            GitUp(sparse=True).version_info()
        return

    if quiet:
        sys.stdout = StringIO()

    try:
        gitup = GitUp()

        if push is not None:
            gitup.settings['push.auto'] = push

        # if arguments['--no-fetch'] or arguments['--no-f']:
        if no_fetch:
            gitup.should_fetch = False

    except GitError:
        sys.exit(1)  # Error in constructor
    else:
        gitup.run()
1198987
function dependencyMatch (expected, actual) {
  // expand github:user/repo#hash to git://github.com/...
  if (expected.indexOf('github:') === 0) {
    expected = expected.replace(/^github:/, 'git://github.com/')
    var parsed = url.parse(expected)
    parsed.pathname += '.git'
    expected = url.format(parsed)
  }

    // normalize git+https prefix
  actual = actual.replace(/^git\+https/, 'git')
  expected = expected.replace(/^git\+https/, 'git')

  expected = ngu(expected)
  actual = ngu(actual)

  expected.url = expected.url.replace('https://', 'git://')
  actual.url = actual.url.replace('https://', 'git://')

  if (expected.url !== actual.url) {
    return false
  }

  if (actual.branch && actual.branch.indexOf(expected.branch) !== 0) {
    return false
  }

  return true
}