Parses the given content for a valid changelog
    :param name: str, package name
    :param content: str, content
    :param releases: list, releases
    :param get_head_fn: function
    :return: dict, changelog
357727
def parse(name, content, releases, get_head_fn):
    
    changelog = {}
    releases = frozenset(releases)
    head = False
    date_line = None
    for line in content.splitlines():
        if DATE_RE.match(line):
            date_line = line
            continue
        if line.strip().startswith("PyAudio"):
            try:
                head = line.strip().split()[1]
            except:
                continue
            changelog[head] = date_line + "\n"
            continue
        if not head:
            continue
        line = line.replace("@", "")
        line = line.replace("#", "")
        changelog[head] += line + "\n"
    return changelog
1264829
def add_release_to_changelog(version):
    """"""
    temp_file = changelog_file().parent / ("~" + changelog_file().name)
    now = datetime.today()
    release_added = False
    with open(str(temp_file), 'w') as g:
        with open(str(changelog_file()), 'r') as f:
            for line in f:
                list_match = list_match_re.match(line)
                if list_match and not release_added:
                    release_line = "{}{} :release:`{} <{}-{:02}-{:02}>`".format(
                                        list_match.group("leading"),
                                        list_match.group("mark"),
                                        version, now.year, now.month, now.day)
                    print(release_line, file=g)
                    release_added = True
                print(line, file=g, end="")
            if not release_added:
                release_line = "{}{} :release:`{} <{}-{:02}-{:02}>`".format(
                                " ", "-", version, now.year, now.month, now.day)
                print(release_line, file=g)
        print('', file=g)  # add a blank line at the end of the file
    shutil.copyfile(str(temp_file), str(changelog_file()))
    os.remove(str(temp_file))
1365209
def have_you_updated_changelog?
      if changelog_changes?
        true
      else
        markdown <<-MARKDOWN
Here's an example of a #{filename} entry:

```markdown
#{Danger::Changelog::ChangelogEntryLine.example(github)}
```
        MARKDOWN
        warn "Unless you're refactoring existing code or improving documentation, please update #{filename}.", sticky: false
        false
      end
    end
957145
def _update_release_content(self, release, content):
        """"""
        if release.body:
            new_body = []
            current_parser = None
            is_start_line = False
            for parser in self.parsers:
                parser.replaced = False

            # update existing sections
            for line in release.body.splitlines():

                if current_parser:
                    if current_parser._is_end_line(current_parser._process_line(line)):
                        parser_content = current_parser.render()
                        if parser_content:
                            # replace existing section with new content
                            new_body.append(parser_content + "\r\n")
                        current_parser = None

                for parser in self.parsers:
                    if (
                        parser._render_header().strip()
                        == parser._process_line(line).strip()
                    ):
                        parser.replaced = True
                        current_parser = parser
                        is_start_line = True
                        break
                    else:
                        is_start_line = False

                if is_start_line:
                    continue
                if current_parser:
                    continue
                else:
                    # preserve existing sections
                    new_body.append(line.strip())

            # catch section without end line
            if current_parser:
                new_body.append(current_parser.render())

            # add new sections at bottom
            for parser in self.parsers:
                parser_content = parser.render()
                if parser_content and not parser.replaced:
                    new_body.append(parser_content + "\r\n")

            content = u"\r\n".join(new_body)

        return content
190525
def get_head(self) -> Commit:
        
        head_commit = self.repo.head.commit
        return Commit(head_commit, self.path, self.main_branch)
902473
def create_or_update_release(user, pwd, secret, repo_slug, changelog_file, doc_url, data_file, tag):
    
    # 1- AUTHENTICATION
    if user is not None and secret is None:
        # using username and password
        # validate('user', user, instance_of=str)
        assert isinstance(user, str)
        # validate('pwd', pwd, instance_of=str)
        assert isinstance(pwd, str)
        g = Github(user, pwd)
    elif user is None and secret is not None:
        # or using an access token
        # validate('secret', secret, instance_of=str)
        assert isinstance(secret, str)
        g = Github(secret)
    else:
        raise ValueError("You should either provide username/password OR an access token")
    click.echo("Logged in as {user_name}".format(user_name=g.get_user()))

    # 2- CHANGELOG VALIDATION
    regex_pattern = "[\s\S]*[\n][#]+[\s]*(?P<title>[\S ]*%s[\S ]*)[\n]+?(?P<body>[\s\S]*?)[\n]*?(\n#|$)" % re.escape(tag)
    changelog_section = re.compile(regex_pattern)
    if changelog_file is not None:
        # validate('changelog_file', changelog_file, custom=os.path.exists,
        #          help_msg="changelog file should be a valid file path")
        assert os.path.exists(changelog_file), "changelog file should be a valid file path"
        with open(changelog_file) as f:
            contents = f.read()

        match = changelog_section.match(contents).groupdict()
        if match is None or len(match) != 2:
            raise ValueError("Unable to find changelog section matching regexp pattern in changelog file.")
        else:
            title = match['title']
            message = match['body']
    else:
        title = tag
        message = ''

    # append footer if doc url is provided
    message += "\n\nSee [documentation page](%s) for details." % doc_url

    # 3- REPOSITORY EXPLORATION
    # validate('repo_slug', repo_slug, instance_of=str, min_len=1, help_msg="repo_slug should be a non-empty string")
    assert isinstance(repo_slug, str) and len(repo_slug) > 0, "repo_slug should be a non-empty string"
    repo = g.get_repo(repo_slug)

    # -- Is there a tag with that name ?
    try:
        tag_ref = repo.get_git_ref("tags/" + tag)
    except UnknownObjectException:
        raise ValueError("No tag with name %s exists in repository %s" % (tag, repo.name))

    # -- Is there already a release with that tag name ?
    click.echo("Checking if release %s already exists in repository %s" % (tag, repo.name))
    try:
        release = repo.get_release(tag)
        if release is not None:
            raise ValueError("Release %s already exists in repository %s. Please set overwrite to True if you wish to "
                             "update the release (Not yet supported)" % (tag, repo.name))
    except UnknownObjectException:
        # Release does not exist: we can safely create it.
        click.echo("Creating release %s on repo: %s" % (tag, repo.name))
        click.echo("Release title: '%s'" % title)
        click.echo("Release message:\n--\n%s\n--\n" % message)
        repo.create_git_release(tag=tag, name=title,
                                message=message,
                                draft=False, prerelease=False)

        # add the asset file if needed
        if data_file is not None:
            release = None
            while release is None:
                release = repo.get_release(tag)
            release.upload_asset(path=data_file, label=path.split(data_file)[1], content_type="application/gzip")
870322
def parse_meta(content, meta_name, source_descr, content_attr_name="content"):
    
    dom = dhtmlparser.parseString(content)

    meta_tags = dom.find(
        "meta",
        fn=lambda x: x.params.get("name", "").lower() == meta_name.lower()
    )

    return [
        SourceString(tag.params[content_attr_name], source_descr)
        for tag in meta_tags
        if content_attr_name in tag.params
    ]
743887
def parse(self, name):
		
		name = name.strip()
		groups = self._parseFedora(name)
		if groups:
			self._signature = DistributionNameSignature("Fedora", groups.group(1))
			return self

		raise ValueError("Distribution name '%s' not recognized" % name)
69300
def generate_changelog(context):
    """"""

    changelog_content = [
        '\n## [%s](%s/compare/%s...%s)\n\n'
        % (
            context.new_version,
            context.repo_url,
            context.current_version,
            context.new_version,
        )
    ]

    git_log_content = None
    git_log = 'log --oneline --no-merges --no-color'.split(' ')
    try:
        git_log_tag = git_log + ['%s..master' % context.current_version]
        git_log_content = git(git_log_tag)
        log.debug('content: %s' % git_log_content)
    except Exception:
        log.warn('Error diffing previous version, initial release')
        git_log_content = git(git_log)

    git_log_content = replace_sha_with_commit_link(context.repo_url, git_log_content)
    # turn change log entries into markdown bullet points
    if git_log_content:
        [
            changelog_content.append('* %s\n' % line) if line else line
            for line in git_log_content[:-1]
        ]

    write_new_changelog(
        context.repo_url, 'CHANGELOG.md', changelog_content, dry_run=context.dry_run
    )
    log.info('Added content to CHANGELOG.md')
    context.changelog_content = changelog_content
44668
def _parse_version(version):
        
        parsed_version = parse_version(version)
        return tuple(
            int(dot_version)
            for dot_version in parsed_version.base_version.split('.')
        ) + (parsed_version.is_prerelease,)
42942
def load(cls, fname):
        
        with open(fname) as f:
            content = f.readlines()
        return Flow.from_json(''.join(content))
504818
def read_version():
    
    regex = re.compile('^(?P<number>\d.*?) .*$')

    with open('../CHANGELOG.rst') as f:
        for line in f:
            match = regex.match(line)
            if match:
                return match.group('number')
846959
def _parse_version(self, line):
        
        version_string = line.split(' ')[1]
        version_list = version_string.split('.')
        major_version = ''.join([version_list[0], version_list[1]])
        release_num = ''.join([version_list[2].rstrip(), "-03"])
        return (major_version, release_num)
841562
def load(cls, filename, name=None):
        
        if not os.path.exists(filename):
            return {}
        name = name or filename

        if name not in cls._conffiles:
            with open(filename) as fdesc:
                content = yaml.load(fdesc, YAMLLoader)
                # in case the file is empty
                if content is None:
                    content = {}
                cls._conffiles[name] = content

        return cls._conffiles[name]
1193529
def build_changelog(docs_path, package_name="yacms"):
    

    project_path = os.path.join(docs_path, "..")
    version_file = os.path.join(package_name, "__init__.py")
    version_var = "__version__"
    changelog_filename = "CHANGELOG"
    changelog_file = os.path.join(project_path, changelog_filename)
    versions = OrderedDict()
    repo = None
    ignore = ("AUTHORS", "formatting", "typo", "pep8", "pep 8",
              "whitespace", "README", "trans", "print debug",
              "debugging", "tabs", "style", "sites", "ignore",
              "tweak", "cleanup", "minor", "for changeset",
              ".com``", "oops", "syntax")
    hotfixes = {
        "40cbc47b8d8a": "1.0.9",
        "a25749986abc": "1.0.10",
    }

    # Load the repo.
    try:
        from mercurial import ui, hg, error
        from mercurial.commands import tag
    except ImportError:
        pass
    else:
        try:
            ui = ui.ui()
            repo = hg.repository(ui, project_path)
        except error.RepoError:
            return
    if repo is None:
        return

    # Go through each changeset and assign it to the versions dict.
    changesets = [repo.changectx(changeset) for changeset in repo.changelog]
    for cs in sorted(changesets, reverse=True, key=_changeset_date):
        # Check if the file with the version number is in this changeset
        # and if it is, pull it out and assign it as a variable.
        files = cs.files()
        new_version = False
        # Commit message cleanup hacks.
        description = cs.description().decode("utf-8")
        description = description.rstrip(".").replace("\n", ". ")
        while "  " in description:
            description = description.replace("  ", " ")
        description = description.replace(". . ", ". ").replace("...", ",")
        while ".." in description:
            description = description.replace("..", ".")
        description = description.replace(":.", ":").replace("n'. t", "n't")
        words = description.split()
        # Format var names in commit.
        for i, word in enumerate(words):
            if (set("._") & set(word[:-1]) and set(letters) & set(word) and
                    "`" not in word and not word[0].isdigit()):
                last = ""
                if word[-1] in ",.":
                    last, word = word[-1], word[:-1]
                words[i] = "``%s``%s" % (word, last)
        description = " ".join(words)
        if version_file in files:
            for line in cs[version_file].data().split("\n"):
                if line.startswith(version_var):
                    exec(line)
                    if locals()[version_var] == "0.1.0":
                        locals()[version_var] = "1.0.0"
                        break
                    versions[locals()[version_var]] = {
                        "changes": [],
                        "date": _changeset_date(cs).strftime("%b %d, %Y")
                    }
                    new_version = len(files) == 1

        # Tag new versions.
        hotfix = hotfixes.get(cs.hex()[:12])
        if hotfix or new_version:
            if hotfix:
                version_tag = hotfix
            else:
                try:
                    version_tag = locals()[version_var]
                except KeyError:
                    version_tag = None
            if version_tag and version_tag not in cs.tags():
                try:
                    tag(ui, repo, version_tag, rev=cs.hex())
                    print("Tagging version %s" % version_tag)
                except:
                    pass

        # Ignore changesets that are merges, bumped the version, closed
        # a branch, regenerated the changelog itself, contain an ignore
        # word, or contain too few words to be meaningful.
        merge = len(cs.parents()) > 1
        branch_closed = len(files) == 0
        changelog_update = changelog_filename in files
        ignored = [w for w in ignore if w.lower() in description.lower()]
        too_few_words = len(description.split()) <= 3
        if (merge or new_version or branch_closed or changelog_update or
                ignored or too_few_words):
            continue
        # Ensure we have a current version and if so, add this changeset's
        # description to it.
        version = None
        try:
            version = locals()[version_var]
        except KeyError:
            if not hotfix:
                continue
        user = cs.user().decode("utf-8").split("<")[0].strip()
        entry = "%s - %s" % (description, user)
        if hotfix or entry not in versions[version]["changes"]:
            if hotfix:
                versions[hotfix] = {
                    "changes": [entry],
                    "date": _changeset_date(cs).strftime("%b %d, %Y"),
                }
            else:
                versions[version]["changes"].insert(0, entry)

    # Write out the changelog.
    with open(changelog_file, "w") as f:
        for version, version_info in versions.items():
            header = "Version %s (%s)" % (version, version_info["date"])
            f.write("%s\n" % header)
            f.write("%s\n" % ("-" * len(header)))
            f.write("\n")
            if version_info["changes"]:
                for change in version_info["changes"]:
                    f.write("  * %s\n" % change)
            else:
                f.write("  * No changes listed.\n")
            f.write("\n")
1094296
def changes(since, out_file, eager):
    """"""
    root = get_root()
    history_data = defaultdict(lambda: {'lines': deque(), 'releasers': set()})

    with chdir(root):
        result = run_command(
            (
                'git log "--pretty=format:%H %s" --date-order --date=iso8601 '
                '--since="{}T00:00:00" */CHANGELOG.md'.format(since)
            ),
            capture=True,
            check=True,
        )

        for result_line in result.stdout.splitlines():
            commit_hash, commit_subject = result_line.split(' ', 1)

            if not eager and 'release' not in commit_subject.lower():
                continue

            result = run_command(
                'git show "--pretty=format:%an%n" -U0 {} */CHANGELOG.md'.format(commit_hash), capture=True, check=True
            )

            # Example:
            #
            # <AUTHOR NAME>
            # diff --git a/<INTEGRATION NAME 1>/CHANGELOG.md b/<INTEGRATION NAME 1>/CHANGELOG.md
            # index 89b5a3441..9534019a9 100644
            # --- a/<INTEGRATION NAME 1>/CHANGELOG.md
            # +++ b/<INTEGRATION NAME 1>/CHANGELOG.md
            # @@ -2,0 +3,5 @@
            # +## <RELEASE VERSION> / <RELEASE DATE>
            # +
            # +* <ENTRY>
            # +* <ENTRY>
            # +
            # diff --git a/<INTEGRATION NAME 2>/CHANGELOG.md b/<INTEGRATION NAME 2>/CHANGELOG.md
            # index 89b5a3441..9534019a9 100644
            # --- a/<INTEGRATION NAME 2>/CHANGELOG.md
            # +++ b/<INTEGRATION NAME 2>/CHANGELOG.md
            # @@ -2,0 +3,4 @@
            # +## <RELEASE VERSION> / <RELEASE DATE>
            # +
            # +* <ENTRY>
            # +
            lines = deque(result.stdout.splitlines())
            author_name = lines.popleft().strip()

            patches = []
            for line in lines:
                if line:
                    # New patch
                    if line.startswith('diff --git'):
                        patches.append([])
                    patches[-1].append(line)

            for patch in patches:
                integration = patch[0].split('/')[-2].strip()
                history_data[integration]['releasers'].add(author_name)

                additions = deque()
                for line in reversed(patch):
                    if line.startswith('+'):
                        line = line[1:]
                        # Demote releases to h3
                        if line.startswith('##'):
                            line = '#{}'.format(line)
                        additions.append(line)
                    elif line.startswith('@@'):
                        break

                # Get rid of the header for new integrations
                if additions[-1].startswith('# '):
                    additions.pop()

                # Get rid of blank lines to ensure consistency
                while not additions[0].strip():
                    additions.popleft()
                while not additions[-1].strip():
                    additions.pop()

                history_data[integration]['lines'].appendleft('')
                history_data[integration]['lines'].extendleft(additions)

    output_lines = ['# Changes since {}'.format(since), '']

    for integration, history in sorted(iteritems(history_data)):
        display_name = load_manifest(integration).get('display_name', integration)
        output_lines.append('## {}'.format(display_name))
        output_lines.append('released by: {}'.format(', '.join(sorted(history['releasers']))))

        output_lines.append('')
        output_lines.extend(history['lines'])

    output = '\n'.join(output_lines)

    if out_file:
        write_file(out_file, output)
    else:
        echo_info(output)
611195
private void extractConfigureScriptEvidence(Dependency dependency,
            final String name, final String contents) {
        final Matcher matcher = PACKAGE_VAR.matcher(contents);
        while (matcher.find()) {
            final String variable = matcher.group(1);
            final String value = matcher.group(2);
            if (!value.isEmpty()) {
                if (variable.endsWith("NAME")) {
                    dependency.addEvidence(EvidenceType.PRODUCT, name, variable, value, Confidence.HIGHEST);
                } else if ("VERSION".equals(variable)) {
                    dependency.addEvidence(EvidenceType.VERSION, name, variable, value, Confidence.HIGHEST);
                } else if ("BUGREPORT".equals(variable)) {
                    dependency.addEvidence(EvidenceType.VENDOR, name, variable, value, Confidence.HIGH);
                } else if ("URL".equals(variable)) {
                    dependency.addEvidence(EvidenceType.VENDOR, name, variable, value, Confidence.HIGH);
                }
            }
        }
    }