Lints a git repository [default command]
6561
def lint(ctx):
    
    lint_config = ctx.obj[0]
    msg_filename = ctx.obj[3]

    # Let's determine where our input data is coming from:
    # Order of precedence:
    # 1. Any data specified via --msg-filename
    # 2. Any data sent to stdin
    # 3. Fallback to reading from local repository
    stdin_input = get_stdin_data()
    if msg_filename:
        LOG.debug("Attempting to read from --msg-filename.")
        gitcontext = GitContext.from_commit_msg(ustr(msg_filename.read()))
    elif stdin_input:
        LOG.debug("No --msg-filename flag. Attempting to read from stdin.")
        gitcontext = GitContext.from_commit_msg(stdin_input)
    else:
        LOG.debug("No --msg-filename flag, no or empty data passed to stdin. Attempting to read from the local repo.")
        gitcontext = GitContext.from_local_repository(lint_config.target, ctx.obj[2])

    number_of_commits = len(gitcontext.commits)
    # Exit if we don't have commits in the specified range. Use a 0 exit code, since a popular use-case is one
    # where users are using --commits in a check job to check the commit messages inside a CI job. By returning 0, we
    # ensure that these jobs don't fail if for whatever reason the specified commit range is empty.
    if number_of_commits == 0:
        LOG.debug(u'No commits in range "%s"', ctx.obj[2])
        ctx.exit(0)

    general_config_builder = ctx.obj[1]
    last_commit = gitcontext.commits[-1]

    # Let's get linting!
    first_violation = True
    exit_code = 0
    for commit in gitcontext.commits:
        # Build a config_builder taking into account the commit specific config (if any)
        config_builder = general_config_builder.clone()
        config_builder.set_config_from_commit(commit)

        # Create a deepcopy from the original config, so we have a unique config object per commit
        # This is important for configuration rules to be able to modifying the config on a per commit basis
        commit_config = config_builder.build(copy.deepcopy(lint_config))

        # Actually do the linting
        linter = GitLinter(commit_config)
        violations = linter.lint(commit)
        # exit code equals the total number of violations in all commits
        exit_code += len(violations)
        if violations:
            # Display the commit hash & new lines intelligently
            if number_of_commits > 1 and commit.sha:
                linter.display.e(u"{0}Commit {1}:".format(
                    "\n" if not first_violation or commit is last_commit else "",
                    commit.sha[:10]
                ))
            linter.print_violations(violations)
            first_violation = False

    # cap actual max exit code because bash doesn't like exit codes larger than 255:
    # http://tldp.org/LDP/abs/html/exitcodes.html
    exit_code = min(MAX_VIOLATION_ERROR_CODE, exit_code)
    LOG.debug("Exit Code = %s", exit_code)
    ctx.exit(exit_code)
1012981
function gitTag () {
      // If the tag exists, skip tagging
      if (shelljs.exec('git ls-remote --tags --exit-code ' + remoteName + ' ' + options.tag, {silent: true}).code === 0) {
        log.subhead('The tag "' + options.tag + '" already exists on remote. Skipping tagging.');
        return;
      }

      log.subhead('Tagging the local repository with ' + options.tag);
      execWrap('git tag ' + options.tag);
    }
469927
function gitTags(wd) {
  const basename = path.basename(wd);
  const keys = ['tag_name', 'datetime_created'];
  const separator = '_,,,_';
  const cmd = `git for-each-ref --format='%(refname:short)${separator}%(taggerdate)' refs/tags`;

  console.log(`Collecting git tags of repo ${chalk.cyan(basename)}`);
  const gitProcess = exec(cmd, {
    cwd: wd
  });
  const rl = readline.createInterface({
    input: gitProcess.stdout
  });

  const tagStats = [];
  return new Promise((resolve, reject) => {
    gitProcess.on('error', (err) => {
      reject(err);
    });

    rl.on('line', (line) => {
      const entry = line.split(separator);
      tagStats.push({
        tag_name: entry[0],
        datetime_created: new Date(entry[1]).toISOString()
      });
    }).on('close', () => {
      if (tagStats.length === 0) {
        reject(new Error(chalk.red(`No tags added to this repo`)));
      }
      resolve(tagStats);
    });

  });
}
1319169
function lint(files) {
  return gulp.src(files)
    .pipe($.plumber())
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failOnError())
    .pipe($.jscs())
    .pipe($.jscs.reporter())
    .pipe($.jscs.reporter('fail'))
    .on('error', onError);
}
1084715
function lint() {
    return gulp.src(srcDir + '**/*.js')
        .pipe($$.excludeGitignore())
        .pipe($$.eslint())
        .pipe($$.eslint.format())
        .pipe($$.eslint.failAfterError());
}
902040
def clone(cls, srcpath, destpath, encoding='utf-8'):
        """"""
        cmd = [GIT, 'clone', '--quiet', '--bare', srcpath, destpath]
        subprocess.check_call(cmd)
        return cls(destpath, encoding)
565866
function clone(repo, targetPath, opts, cb) {
  opts = opts || {};
  var git = opts.git || 'git';
  var args = ['clone'];

  if (opts.shallow) {
    args.push('--depth');
    args.push('1');
  }

  args.push('--');
  args.push(repo);
  args.push(targetPath);

  var process = spawn(git, args);
  process.on('close', function(status) {
    if (status === 0) {
      if (opts.checkout) {
        _checkout();
      } else {
        cb && cb();
      }
    } else {
      cb && cb(new Error("'git clone' failed with status " + status));
    }
  });

  function _checkout() {
    var args = ['checkout', opts.checkout];
    var process = spawn(git, args, { cwd: targetPath });
    process.on('close', function(status) {
      if (status === 0) {
        cb && cb();
      } else {
        cb && cb(new Error("'git checkout' failed with status " + status));
      }
    });
  }
}
861402
def _git_version():
    """"""

    import subprocess
    import os

    def _minimal_ext_cmd(cmd):
        # construct minimal environment
        env = {}
        for k in ['SYSTEMROOT', 'PATH']:
            v = os.environ.get(k)
            if v is not None:
                env[k] = v
        # LANGUAGE is used on win32
        env['LANGUAGE'] = 'C'
        env['LANG'] = 'C'
        env['LC_ALL'] = 'C'
        FNULL = open(os.devnull, 'w')
        cwd = os.path.dirname(os.path.realpath(__file__))
        proc = subprocess.Popen(
            cmd, stdout=subprocess.PIPE, stderr=FNULL, env=env, cwd=cwd)
        out = proc.communicate()[0]
        return out

    try:
        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
        return out.strip().decode('ascii')
    except OSError:
        return "unknown"
85450
function git(args) {
  return new Promise((resolve, reject) => {
    exec(`git ${args}`, (err, stdout) => {
      if (err) {
        reject(err);
      } else {
        resolve(stdout.trim());
      }
    });
  });
}
882217
function cmd(args) {
            var def = Q.defer();
            grunt.util.spawn({ cmd: 'git', args: args }, def.resolve);
            return def.promise;
        }
396690
def _lint():
    """"""
    # Flake8 doesn't have an easy way to run checks using a Python function, so
    # just fork off another process to do it.

    # Python 3 compat:
    # - The result of subprocess call outputs are byte strings, meaning we need
    #   to pass a byte string to endswith.
    project_python_files = [filename for filename in get_project_files()
                            if filename.endswith(b'.py')]
    retcode = subprocess.call(
        ['flake8', '--max-complexity=10'] + project_python_files)
    if retcode == 0:
        print_success_message('No style errors')
    return retcode
414914
def git_all(*args, git=maybeloggit, **kwargs):
    ''

    try:
        cmd = git(*args, _err_to_out=True, _decode_errors='replace', **kwargs)
        out = cmd.stdout
    except sh.ErrorReturnCode as e:
        status('exit_code=%s' % e.exit_code)
        out = e.stdout

    out = out.decode('utf-8')

    return out
479507
def init(path = Dir.pwd, options = {})
      exit_status = FalkorLib::Git.init(path, options)
      unless command?('git-flow')
        # Check (mainly for Linux) if the command is not available under `/usr/lib/git-core`
        git_lib = '/usr/lib/git-core/'
        error "you shall install git-flow: see https://github.com/nvie/gitflow/wiki/Installation" unless File.exist?(File.join(git_lib, 'git-flow'))
      end
      remotes      = FalkorLib::Git.remotes(path)
      git_root_dir = FalkorLib::Git.rootdir( path )
      Dir.chdir( git_root_dir ) do
        unless FalkorLib::Git.commits?( git_root_dir)
          warn "Not yet any commit detected in this repository."
          readme = 'README.md'
          unless File.exist?( readme )
            answer = ask(cyan("=> initialize a commit with an [empty] #{readme} file (Y|n)?"), 'Yes')
            exit 0 if answer =~ /n.*/i
            FileUtils.touch(readme)
          end
          FalkorLib::Git.add(readme, "Initiate the repository with a '#{readme}' file")
        end
        branches = FalkorLib::Git.list_branch(path)
        gitflow_branches = FalkorLib.config.gitflow[:branches].clone
        # correct eventually the considered branch from the options
        gitflow_branches.each do |t, _b|
          gitflow_branches[t] = options[t.to_sym] if options[t.to_sym]
          confs = FalkorLib::Git.config('gitflow*', path, :hash => true)
          gitflow_branches[t] = confs["gitflow.branch.#{t}"] unless confs.empty?
        end
        if options[:interactive]
          gitflow_branches[:master]  = ask("=> branch name for production releases", gitflow_branches[:master])
          gitflow_branches[:develop] = ask("=> branch name for development commits", gitflow_branches[:develop])
        end
        ap gitflow_branches if options[:debug]
        if remotes.include?( 'origin' )
          info "=> configure remote (tracked) branches"
          exit_status = FalkorLib::Git.fetch(path)
          gitflow_branches.each do |_type, branch|
            if branches.include? "remotes/origin/#{branch}"
              exit_status = FalkorLib::Git.grab(branch, path)
            else
              unless branches.include? branch
                info "=> creating the branch '#{branch}'"
                FalkorLib::Git.create_branch( branch, path )
              end
              exit_status = FalkorLib::Git.publish(branch, path )
            end
          end
        else
          gitflow_branches.each do |_type, branch|
            unless branches.include? branch
              info " => creating the branch '#{branch}'"
              exit_status = FalkorLib::Git.create_branch( branch, path )
            end
          end
        end
        #info "initialize git flow configs"
        gitflow_branches.each do |t, branch|
          exit_status = execute "git config gitflow.branch.#{t} #{branch}"
        end
        FalkorLib.config.gitflow[:prefix].each do |t, prefix|
          exit_status = execute "git config gitflow.prefix.#{t} #{prefix}"
        end
        devel_branch = gitflow_branches[:develop]
        #info "checkout to the main development branch '#{devel_branch}'"
        exit_status = run %(
                   git checkout #{devel_branch}
                )
        # git config branch.$(git rev-parse --abbrev-ref HEAD).mergeoptions --no-edit for the develop branch
        exit_status = execute "git config branch.#{devel_branch}.mergeoptions --no-edit"
        if branches.include?('master') && !gitflow_branches.values.include?( 'master' )
          warn "Your git-flow confuguration does not hold the 'master' branch any more"
          warn "You probably want to get rid of it asap by running 'git branch -d master'"
        end
        if devel_branch != 'master' &&
           remotes.include?( 'origin' ) &&
           branches.include?( 'remotes/origin/master')
          warn "You might want to change the remote default branch to point to '#{devel_branch}"
          puts "=> On github: Settings > Default Branch > #{devel_branch}"
          puts "=> On the remote bare Git repository: 'git symbolic-ref HEAD refs/head/#{devel_branch}'"
        end
      end
      exit_status
    end
1036441
def lint(commit = nil)
      files = pronto(commit)
      return if files.empty?

      markdown offenses_message(files)
    end
607387
def rm(pattern):
    """"""
    paths = glob.glob(pattern)
    for path in paths:
        if path.startswith('.git/'):
            continue
        if os.path.isdir(path):
            def onerror(fun, path, excinfo):
                exc = excinfo[1]
                if exc.errno != errno.ENOENT:
                    raise

            safe_print("rmdir -f %s" % path)
            shutil.rmtree(path, onerror=onerror)
        else:
            safe_print("rm %s" % path)
            os.remove(path)
623587
def run!
      git  = nil
      path = nil

      return show_usage() if ARGV.length < 1
      name = ARGV.shift() if ARGV.first[ 0 ] != '-'

      opts = GetoptLong.new(
        [ '--help',    '-h',       GetoptLong::NO_ARGUMENT       ],
        [ '--version', '-v', '-V', GetoptLong::NO_ARGUMENT       ],
        [ '--path',    '-p',       GetoptLong::REQUIRED_ARGUMENT ],
        [ '--from',    '-f',       GetoptLong::REQUIRED_ARGUMENT ],
        [ '--git',     '-g',       GetoptLong::REQUIRED_ARGUMENT ],
      )

      silence_stream( $stderr ) do
        begin
          opts.each do | opt, arg |
            case opt
              when '--help'
                return show_usage()
              when '--version'
                return show_version()
              when '--path'
                path = arg
              when '--from', '--git'
                git = arg
            end
          end

        rescue GetoptLong::InvalidOption, GetoptLong::MissingArgument => e
          return usage_and_warning( e.message )

        end
      end

      unless path.nil? || git.nil?
        return usage_and_warning( 'Use the --path OR --from arguments, but not both' )
      end

      git ||= 'git@github.com:LoyaltyNZ/service_shell.git'

      name = ARGV.shift() if name.nil?
      return show_usage() if name.nil?

      return usage_and_warning( "Unexpected extra arguments were given" ) if ARGV.count > 0
      return usage_and_warning( "SERVICE_NAME must match #{ NAME_REGEX.inspect }" ) if naughty_name?( name )
      return usage_and_warning( "'#{ name }' already exists" ) if File.exist?( "./#{ name }" )

      return create_service( name, git, path )
    end
169305
async function initRepo({
  repository,
  endpoint,
  gitPrivateKey,
  gitFs,
  localDir,
}) {
  logger.debug(
    `initRepo("${JSON.stringify(
      { repository, endpoint, gitFs, localDir },
      null,
      2
    )}")`
  );
  const opts = hostRules.find({ platform }, { endpoint });
  // istanbul ignore if
  if (!(opts.username && opts.password)) {
    throw new Error(
      `No username/password found for Bitbucket repository ${repository}`
    );
  }
  // istanbul ignore if
  if (!opts.endpoint) {
    throw new Error(`No endpoint found for Bitbucket Server`);
  }
  hostRules.update({ ...opts, platform, default: true });
  api.reset();

  const [projectKey, repositorySlug] = repository.split('/');
  config = { projectKey, repositorySlug, gitPrivateKey };

  // Always gitFs
  const { host, pathname } = url.parse(opts.endpoint);
  const gitUrl = GitStorage.getUrl({
    gitFs: gitFs || 'https',
    auth: `${opts.username}:${opts.password}`,
    host: `${host}${pathname}${pathname.endsWith('/') ? '' : '/'}scm`,
    repository,
  });

  config.storage = new GitStorage();
  await config.storage.initRepo({
    ...config,
    localDir,
    url: gitUrl,
  });

  const platformConfig = {};

  try {
    const info = (await api.get(
      `./rest/api/1.0/projects/${config.projectKey}/repos/${
        config.repositorySlug
      }`
    )).body;
    platformConfig.privateRepo = info.is_private;
    platformConfig.isFork = !!info.parent;
    platformConfig.repoFullName = info.name;
    config.owner = info.project.key;
    logger.debug(`${repository} owner = ${config.owner}`);
    config.defaultBranch = (await api.get(
      `./rest/api/1.0/projects/${config.projectKey}/repos/${
        config.repositorySlug
      }/branches/default`
    )).body.displayId;
    config.baseBranch = config.defaultBranch;
    config.mergeMethod = 'merge';
  } catch (err) /* istanbul ignore next */ {
    logger.debug(err);
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    logger.info({ err }, 'Unknown Bitbucket initRepo error');
    throw err;
  }
  delete config.prList;
  delete config.fileList;
  logger.debug(
    { platformConfig },
    `platformConfig for ${config.projectKey}/${config.repositorySlug}`
  );
  return platformConfig;
}