Current commit parser

    :raises ImproperConfigurationError: if ImportError or AttributeError is raised
16887
def current_commit_parser() -> Callable:
    

    try:
        parts = config.get('semantic_release', 'commit_parser').split('.')
        module = '.'.join(parts[:-1])
        return getattr(importlib.import_module(module), parts[-1])
    except (ImportError, AttributeError) as error:
        raise ImproperConfigurationError('Unable to import parser "{}"'.format(error))
1180483
def commit(self, commit):
		
		try:
			return self._commitData(self.repo.commit(commit))
		except (ValueError, KeyError, BadObject):
			if self._repo_info:
				raise KeyError("Commit %s not found for %s" % (commit, str(self._repo_info)))
			else:
				raise KeyError("Commit %s not found" % commit)
131579
def parse_commit_url(url)
      begin
        parts = URI.parse(@commit_url).path.split("/")
        nwo = "#{parts[1]}/#{parts[2]}"
        sha = parts[4]
        return nwo, sha
      rescue
        raise ContributionChecker::InvalidCommitUrlError
      end
    end
1038233
def commit_status(base_commit, new_commit, ignore: [])
      base_tree = get_object(base_commit.tree) unless base_commit.nil?
      new_tree  = get_object(new_commit.tree)  unless new_commit.nil?

      Utils::Status.compare_trees base_tree,
                                  new_tree,
                                  object_store,
                                  ignore: ignore
    end
801424
def import_from_settings(attr, *args):
    
    try:
        if args:
            return getattr(settings, attr, args[0])
        return getattr(settings, attr)
    except AttributeError:
        raise ImproperlyConfigured('Setting {0} not found'.format(attr))
850782
def _parse_global_section(self, cfg_handler):
        
        # global configuration
        if 'versionner' in cfg_handler:
            cfg = cfg_handler['versionner']
            if 'file' in cfg:
                self.version_file = cfg['file']
            if 'date_format' in cfg:
                self.date_format = cfg['date_format']
            if 'up_part' in cfg:
                self.up_part = cfg['up_part']
            if 'default_init_version' in cfg:
                self.default_init_version = cfg['default_init_version']
            if 'default_increase_value' in cfg:
                self.default_increase_value = cfg.getint('default_increase_value')
983591
def raise_for_old_graph(graph):
    
    graph_version = tokenize_version(graph.pybel_version)
    if graph_version < PYBEL_MINIMUM_IMPORT_VERSION:
        raise ImportVersionWarning(graph_version, PYBEL_MINIMUM_IMPORT_VERSION)
507680
def set_commit(self, commit, logmsg=None):
        """"""
        # check the type - assume the best if it is a base-string
        invalid_type = False
        if isinstance(commit, Object):
            invalid_type = commit.type != Commit.type
        elif isinstance(commit, SymbolicReference):
            invalid_type = commit.object.type != Commit.type
        else:
            try:
                invalid_type = self.repo.rev_parse(commit).type != Commit.type
            except (BadObject, BadName):
                raise ValueError("Invalid object: %s" % commit)
            # END handle exception
        # END verify type

        if invalid_type:
            raise ValueError("Need commit, got %r" % commit)
        # END handle raise

        # we leave strings to the rev-parse method below
        self.set_object(commit, logmsg)

        return self
1021252
def fix_code(code, directory):
    
    if not black:
        raise Fault("black not installed", code=400)

    try:
        if parse_version(black.__version__) < parse_version("19.0"):
            reformatted_source = black.format_file_contents(
                src_contents=code, line_length=black.DEFAULT_LINE_LENGTH, fast=False
            )
        else:
            fm = black.FileMode()
            reformatted_source = black.format_file_contents(
                src_contents=code, fast=False, mode=fm
            )
        return reformatted_source
    except black.NothingChanged:
        return code
    except Exception as e:
        raise Fault("Error during formatting: {}".format(e), code=400)
1085889
def refactor(module, name, repl):
        
        name = nstr(name)

        # import a module when refactoring based on a string
        if isinstance(module, basestring):
            try:
                module = __import__(module)
            except ImportError:
                logger.exception('Could not import module: %s' % module)
                return False

        try:
            glbls = module.__dict__
        except AttributeError:
            err = '%s cannot support refactoring.' % module.__name__
            logger.exception(err)
            return False

        if name in glbls:
            # refactor the value
            glbls[name] = repl

            return True
        else:
            err = '%s is not a member of %s.' % (name, module.__name__)
            logger.warning(err)
            return False
1194816
def parse_arguments():
    """"""
    parser = create_parser()
    args = parser.parse_args()
    if not args.role_requirements_old_commit:
        args.role_requirements_old_commit = args.role_requirements
    if not args.rpc_product_old_commit:
        args.rpc_product_old_commit = args.rpc_product
    return args
914025
def main(cmd_args: list = None) -> None:
    
    parser = argparse.ArgumentParser(description='Auto-versioning utility.')
    subparsers = parser.add_subparsers()

    infer_parser = subparsers.add_parser('infer', help='Infers next version.')
    infer_parser.set_defaults(func=infer)

    commit_parser = subparsers.add_parser('commit',
                                          help='Makes release commit.')
    commit_parser.set_defaults(func=commit)

    bump_parser = subparsers.add_parser('bump', help='Bumps version.')
    bump_parser.add_argument('type', nargs='?', default='patch',
                             choices=['patch', 'minor', 'major'],
                             help='The type of version to bump.')
    bump_parser.set_defaults(func=bump)

    try:
        if cmd_args:
            args = parser.parse_args(cmd_args)
        else:
            args = parser.parse_args()

        args.func(args)
    except AttributeError:
        parser.print_help()
1081776
def diff_objects(self, latest_commit_sha):
        
        base = ['git', '--bare', '--git-dir', self.git_path]

        object_shas = []
        summary = {'commits': [], 'trees': [], 'files': []}

        def read_parents_and_tree_from(commit):
            if commit in self.synced_object_shas or commit in object_shas:
                # this commit has already been synced or read
                return None, None

            self.synced_object_shas[commit] = True
            summary['commits'].append(commit)
            object_shas.append(commit)

            object_content = subprocess.check_output(base + ['cat-file', '-p', commit]).decode('utf-8').strip()
            parents = []
            tree = ''
            for line in object_content.splitlines():
                if line.startswith('tree '):
                    tree = line[len('tree '):]
                if line.startswith('parent '):
                    parents.append(line[len('parent '):])

            return parents, tree

        def collect_files_from_tree(tree):
            if tree in self.synced_object_shas or tree in object_shas:
                # we have exactly this tree already synced or read, meaning all its objects as well
                return

            self.synced_object_shas[tree] = True
            summary['trees'].append(tree)
            object_shas.append(tree)

            object_content = subprocess.check_output(base + ['ls-tree', '-r', '-t', tree]).decode('utf-8').strip()

            for line in object_content.splitlines():
                exploded = line.split(' ')

                if len(exploded) < 3:
                    sys.stderr.write("Error: Wrong line format of ls-tree for %s: %s\n" % (tree, line,))
                    sys.exit(1)

                object_to_add = str(exploded[2][:40])
                path = str(exploded[2][41:])

                if object_to_add in self.synced_object_shas or object_to_add in object_shas:
                    # have it already in the list or already synced
                    continue

                object_shas.append(object_to_add)
                self.synced_object_shas[object_to_add] = True
                summary['files'].append([object_to_add, path])

        commits_to_check = [latest_commit_sha]

        while len(commits_to_check):
            sha = commits_to_check.pop(0)
            parents, tree = read_parents_and_tree_from(sha)

            if parents:
                for parent in parents:
                    if parent not in commits_to_check:
                        commits_to_check.append(parent)

            if tree:
                collect_files_from_tree(tree)

        is_debug2() and self.logger.debug("shas_to_check %d: %s " % (len(object_shas), str(object_shas),))

        if not object_shas:
            return [], summary

        try:
            is_debug2() and self.logger.debug("Do git-cat-file-check.sh")

            ssh_stream = create_ssh_stream(read_home_config(), exit_on_failure=False)
            channel = ssh_stream.get_transport().open_session()
            channel.exec_command('git-cat-file-check.sh "%s"' % (self.model_name + '.git',))
            channel.sendall('\n'.join(object_shas))
            channel.shutdown_write()

            def readall(c):
                content = b''
                while True:
                    try:
                        chunk = c.recv(1024)
                        if chunk == b'':
                            break
                        content += chunk
                    except (KeyboardInterrupt, SystemExit):
                        return

                return content

            missing_objects = readall(channel).decode('utf-8').splitlines()
            channel.close()
            ssh_stream.close()

            # make sure we have in summary only SHAs we actually will sync
            for stype in six.iterkeys(summary):
                ids = summary[stype][:]
                for sha in ids:
                    if stype == 'files':
                        if sha[0] not in missing_objects:
                            summary[stype].remove(sha)
                    else:
                        if sha not in missing_objects:
                            summary[stype].remove(sha)

            return missing_objects, summary
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception as e:
            self.logger.error("Failed to generate diff_objects: %s" % (str(e),))
            for sha in object_shas:
                if sha in self.synced_object_shas:
                    del self.synced_object_shas[sha]
            return None, None
145497
def _commit(self):
        
        assert self.uri is not None, Exception("BadArgument: uri property cannot be None")
        url = '{}/{}'.format(self.uri, self.__class__.__name__)
        serialized_json = jsonpickle.encode(self, unpicklable=False, )
        headers = {'Content-Type': 'application/json', 'Content-Length': str(len(serialized_json))}
        response = Http.post(url=url, data=serialized_json, headers=headers)
        if response.status_code != 200:
            from ArubaCloud.base.Errors import MalformedJsonRequest
            raise MalformedJsonRequest("Request: {}, Status Code: {}".format(serialized_json, response.status_code))
        content = jsonpickle.decode(response.content.decode("utf-8"))
        if content['ResultCode'] == 17:
            from ArubaCloud.base.Errors import OperationAlreadyEnqueued
            raise OperationAlreadyEnqueued("{} already enqueued".format(self.__class__.__name__))
        if content['Success'] is False:
            from ArubaCloud.base.Errors import RequestFailed
            raise RequestFailed("Request: {}, Response: {}".format(serialized_json, response.content))
        return content
134440
def infer(args: argparse.Namespace) -> None:
    
    try:
        last_tag = last_git_release_tag(git_tags())
    except NoGitTagsException:
        print(SemVer(0, 1, 0))
        exit(0)

    commit_log = git_commits_since_last_tag(last_tag)
    action = parse_commit_log(commit_log)

    last_ver = git_tag_to_semver(last_tag)

    if action == 'min':
        new_ver = last_ver.bump_minor()
    elif action == 'maj':
        new_ver = last_ver.bump_major()
    else:
        new_ver = last_ver.bump_patch()

    print(new_ver)
500911
def check_py(self, version, name, original, loc, tokens):
        """"""
        internal_assert(len(tokens) == 1, "invalid " + name + " tokens", tokens)
        if self.target_info < get_target_info(version):
            raise self.make_err(CoconutTargetError, "found Python " + ".".join(version) + " " + name, original, loc, target=version)
        else:
            return tokens[0]
981501
def main(fixer_pkg, args=None):
    
    # Set up option parser
    parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
    parser.add_option("-d", "--doctests_only", action="store_true",
                      help="Fix up doctests only")
    parser.add_option("-f", "--fix", action="append", default=[],
                      help="Each FIX specifies a transformation; default: all")
    parser.add_option("-j", "--processes", action="store", default=1,
                      type="int", help="Run 2to3 concurrently")
    parser.add_option("-x", "--nofix", action="append", default=[],
                      help="Prevent a transformation from being run")
    parser.add_option("-l", "--list-fixes", action="store_true",
                      help="List available transformations")
    parser.add_option("-p", "--print-function", action="store_true",
                      help="Modify the grammar so that print() is a function")
    parser.add_option("-v", "--verbose", action="store_true",
                      help="More verbose logging")
    parser.add_option("--no-diffs", action="store_true",
                      help="Don't show diffs of the refactoring")
    parser.add_option("-w", "--write", action="store_true",
                      help="Write back modified files")
    parser.add_option("-n", "--nobackups", action="store_true", default=False,
                      help="Don't write backups for modified files")
    parser.add_option("-o", "--output-dir", action="store", type="str",
                      default="", help="Put output files in this directory "
                      "instead of overwriting the input files.  Requires -n.")
    parser.add_option("-W", "--write-unchanged-files", action="store_true",
                      help="Also write files even if no changes were required"
                      " (useful with --output-dir); implies -w.")
    parser.add_option("--add-suffix", action="store", type="str", default="",
                      help="Append this string to all output filenames."
                      " Requires -n if non-empty.  "
                      "ex: --add-suffix='3' will generate .py3 files.")

    # Parse command line arguments
    refactor_stdin = False
    flags = {}
    options, args = parser.parse_args(args)
    if options.write_unchanged_files:
        flags["write_unchanged_files"] = True
        if not options.write:
            warn("--write-unchanged-files/-W implies -w.")
        options.write = True
    # If we allowed these, the original files would be renamed to backup names
    # but not replaced.
    if options.output_dir and not options.nobackups:
        parser.error("Can't use --output-dir/-o without -n.")
    if options.add_suffix and not options.nobackups:
        parser.error("Can't use --add-suffix without -n.")

    if not options.write and options.no_diffs:
        warn("not writing files and not printing diffs; that's not very useful")
    if not options.write and options.nobackups:
        parser.error("Can't use -n without -w")
    if options.list_fixes:
        print "Available transformations for the -f/--fix option:"
        for fixname in refactor.get_all_fix_names(fixer_pkg):
            print fixname
        if not args:
            return 0
    if not args:
        print >> sys.stderr, "At least one file or directory argument required."
        print >> sys.stderr, "Use --help to show usage."
        return 2
    if "-" in args:
        refactor_stdin = True
        if options.write:
            print >> sys.stderr, "Can't write to stdin."
            return 2
    if options.print_function:
        flags["print_function"] = True

    # Set up logging handler
    level = logging.DEBUG if options.verbose else logging.INFO
    logging.basicConfig(format='%(name)s: %(message)s', level=level)
    logger = logging.getLogger('lib2to3.main')

    # Initialize the refactoring tool
    avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
    unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
    explicit = set()
    if options.fix:
        all_present = False
        for fix in options.fix:
            if fix == "all":
                all_present = True
            else:
                explicit.add(fixer_pkg + ".fix_" + fix)
        requested = avail_fixes.union(explicit) if all_present else explicit
    else:
        requested = avail_fixes.union(explicit)
    fixer_names = requested.difference(unwanted_fixes)
    input_base_dir = os.path.commonprefix(args)
    if (input_base_dir and not input_base_dir.endswith(os.sep)
        and not os.path.isdir(input_base_dir)):
        # One or more similar names were passed, their directory is the base.
        # os.path.commonprefix() is ignorant of path elements, this corrects
        # for that weird API.
        input_base_dir = os.path.dirname(input_base_dir)
    if options.output_dir:
        input_base_dir = input_base_dir.rstrip(os.sep)
        logger.info('Output in %r will mirror the input directory %r layout.',
                    options.output_dir, input_base_dir)
    rt = StdoutRefactoringTool(
            sorted(fixer_names), flags, sorted(explicit),
            options.nobackups, not options.no_diffs,
            input_base_dir=input_base_dir,
            output_dir=options.output_dir,
            append_suffix=options.add_suffix)

    # Refactor all files and directories passed as arguments
    if not rt.errors:
        if refactor_stdin:
            rt.refactor_stdin()
        else:
            try:
                rt.refactor(args, options.write, options.doctests_only,
                            options.processes)
            except refactor.MultiprocessingUnsupported:
                assert options.processes > 1
                print >> sys.stderr, "Sorry, -j isn't " \
                    "supported on this platform."
                return 1
        rt.summarize()

    # Return error status (0 if rt.errors is zero)
    return int(bool(rt.errors))