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
197470
def parse(name, content, releases, get_head_fn):
    
    try:
        return {e["version"]: e["changelog"] for e in content["entries"]
                if e["changelog"]}
    except KeyError:
        return {}
16195
def changelog(**kwargs):
    
    current_version = get_current_version()
    debug('changelog got current_version', current_version)

    if current_version is None:
        raise ImproperConfigurationError(
            "Unable to get the current version. "
            "Make sure semantic_release.version_variable "
            "is setup correctly"
        )
    previous_version = get_previous_version(current_version)
    debug('changelog got previous_version', previous_version)

    log = generate_changelog(previous_version, current_version)
    click.echo(markdown_changelog(current_version, log, header=False))

    debug('noop={}, post={}'.format(kwargs.get('noop'), kwargs.get('post')))
    if not kwargs.get('noop') and kwargs.get('post'):
        if check_token():
            owner, name = get_repository_owner_and_name()
            click.echo('Updating changelog')
            post_changelog(
                owner,
                name,
                current_version,
                markdown_changelog(current_version, log, header=False)
            )
        else:
            click.echo(
                click.style('Missing token: cannot post changelog', 'red'), err=True)
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)
1160559
def content(self, content):
        
        allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"]
        if not set(content).issubset(set(allowed_values)):
            raise ValueError(
                "Invalid values for `content` [{0}], must be a subset of [{1}]"
                .format(", ".join(map(str, set(content)-set(allowed_values))),
                        ", ".join(map(str, allowed_values)))
            )

        self._content = content
233227
def _versions_from_changelog(changelog):
    
    versions = [Version(x) for x in changelog if BUGFIX_RELEASE_RE.match(x)]
    return sorted(versions)
44235
def get_changeset(args):
    
    # Parse the arguments.
    parser = argparse.ArgumentParser(description=get_changeset.__doc__)
    parser.add_argument(
        'infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin,
        help='path to the bundle YAML file')
    parser.add_argument(
        '--version', action='version', version='%(prog)s {}'.format(version))
    options = parser.parse_args(args)

    # Parse the provided YAML file.
    try:
        bundle = yaml.safe_load(options.infile)
    except Exception:
        return 'error: the provided bundle is not a valid YAML'

    # Validate the bundle object.
    errors = validation.validate(bundle)
    if errors:
        return '\n'.join(errors)

    # Dump the changeset to stdout.
    print('[')
    for num, change in enumerate(changeset.parse(bundle)):
        if num:
            print(',')
        print(json.dumps(change))
    print(']')
1114139
def changelog(ctx, check, version, old_version, initial, quiet, dry_run):
    
    if check not in get_valid_checks():
        abort('Check `{}` is not an Agent-based Integration'.format(check))

    # sanity check on the version provided
    cur_version = old_version or get_version_string(check)
    if parse_version_info(version) <= parse_version_info(cur_version):
        abort('Current version is {}, cannot bump to {}'.format(cur_version, version))

    if not quiet:
        echo_info('Current version of check {}: {}, bumping to: {}'.format(check, cur_version, version))

    # get the name of the current release tag
    target_tag = get_release_tag_string(check, cur_version)

    # get the diff from HEAD
    diff_lines = get_commits_since(check, None if initial else target_tag)

    # for each PR get the title, we'll use it to populate the changelog
    pr_numbers = parse_pr_numbers(diff_lines)
    if not quiet:
        echo_info('Found {} PRs merged since tag: {}'.format(len(pr_numbers), target_tag))

    if initial:
        # Only use the first one
        del pr_numbers[:-1]

    user_config = ctx.obj
    entries = []
    for pr_num in pr_numbers:
        try:
            payload = get_pr(pr_num, user_config)
        except Exception as e:
            echo_failure('Unable to fetch info for PR #{}: {}'.format(pr_num, e))
            continue

        changelog_labels = get_changelog_types(payload)

        if not changelog_labels:
            abort('No valid changelog labels found attached to PR #{}, please add one!'.format(pr_num))
        elif len(changelog_labels) > 1:
            abort('Multiple changelog labels found attached to PR #{}, please only use one!'.format(pr_num))

        changelog_type = changelog_labels[0]
        if changelog_type == CHANGELOG_TYPE_NONE:
            if not quiet:
                # No changelog entry for this PR
                echo_info('Skipping PR #{} from changelog due to label'.format(pr_num))
            continue

        author = payload.get('user', {}).get('login')
        author_url = payload.get('user', {}).get('html_url')
        title = '[{}] {}'.format(changelog_type, payload.get('title'))

        entry = ChangelogEntry(pr_num, title, payload.get('html_url'), author, author_url, from_contributor(payload))

        entries.append(entry)

    # store the new changelog in memory
    new_entry = StringIO()

    # the header contains version and date
    header = '## {} / {}\n'.format(version, datetime.now().strftime('%Y-%m-%d'))
    new_entry.write(header)

    # one bullet point for each PR
    new_entry.write('\n')
    for entry in entries:
        thanks_note = ''
        if entry.from_contributor:
            thanks_note = ' Thanks [{}]({}).'.format(entry.author, entry.author_url)
        new_entry.write('* {}. See [#{}]({}).{}\n'.format(entry.title, entry.number, entry.url, thanks_note))
    new_entry.write('\n')

    # read the old contents
    changelog_path = os.path.join(get_root(), check, 'CHANGELOG.md')
    old = list(stream_file_lines(changelog_path))

    # write the new changelog in memory
    changelog_buffer = StringIO()

    # preserve the title
    changelog_buffer.write(''.join(old[:2]))

    # prepend the new changelog to the old contents
    # make the command idempotent
    if header not in old:
        changelog_buffer.write(new_entry.getvalue())

    # append the rest of the old changelog
    changelog_buffer.write(''.join(old[2:]))

    # print on the standard out in case of a dry run
    if dry_run:
        echo_info(changelog_buffer.getvalue())
    else:
        # overwrite the old changelog
        write_file(changelog_path, changelog_buffer.getvalue())
1186058
def get_content(ident_hash, context=None):
    
    id, version = get_id_n_version(ident_hash)
    filename = 'index.cnxml.html'

    if context is not None:
        stmt = _get_sql('get-baked-content.sql')
        args = dict(id=id, version=version, context=context)
    else:
        stmt = _get_sql('get-content.sql')
        args = dict(id=id, version=version, filename=filename)

    with db_connect() as db_conn:
        with db_conn.cursor() as cursor:
            cursor.execute(stmt, args)
            try:
                content, _ = cursor.fetchone()
            except TypeError:
                raise ContentNotFound(ident_hash, context, filename)
    return content[:]
436098
def parse_commit_log(name, content, releases, get_head_fn):
    
    log = ""
    raw_log = ""
    for path, _ in content:
        log += "\n".join(changelog(repository=GitRepos(path), tag_filter_regexp=r"v?\d+\.\d+(\.\d+)?"))
        raw_log += "\n" + subprocess.check_output(
            ["git", "-C", path, "--no-pager", "log", "--decorate"]).decode("utf-8")
        shutil.rmtree(path)
    log = parse(name, log, releases, get_head_fn)

    return log, raw_log
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)
663500
def get_changelog_types(pr_payload):
    
    changelog_labels = []
    for name in get_pr_labels(pr_payload):
        if name.startswith(CHANGELOG_LABEL_PREFIX):
            # only add the name, e.g. for `changelog/Added` it's just `Added`
            changelog_labels.append(name.split(CHANGELOG_LABEL_PREFIX)[1])

    return changelog_labels
1164698
def get_parsed_data(fn, *args, **kwargs):
    
    file_format = detect_format(fn, *args, **kwargs)
    data = get_header(fn, file_format, *args, **kwargs)
    parsed_data = parse_header(data, *args, **kwargs)
    return parsed_data
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)
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
882979
def getHeadContent(self, req):
        
        site = ixmantissa.ISiteURLGenerator(self.store)
        for t in getInstalledThemes(self.store):
            yield t.head(req, site)
200273
def publish():
    """"""
    print("To be ready for release, remember:")
    print("      1) Update the version number (and associated test)")
    print("      2) Update the ChangeLog.rst (and other documentation)")
    print(
        "         ChangeLog should have an line (title) consisting of the version number"
    )
    print("      3) Tag Mercurial with 'Release <version>'")
    print("      4) Push updates to BitBucket")
    print("      5) Set the RELEASE environment variable")
    print("           $ export RELEASE=formic")

    cmd = [
        'bash', '-c',
        'yolk -M formic | grep "^version: " | sed "s/^version: \\(.*\\)$/\\1/"'
    ]
    published_version = subprocess.check_output(cmd).strip()
    our_version = open(os.path.join("formic", "VERSION.txt"), "r").read()

    # sanity test on version
    if "\n" in published_version or\
       len(published_version) < 3 or len(published_version) > 10:
        raise Exception(
            "Published version number seems weird: " + published_version)

    print("Published version:", published_version)
    print("Current version:  ", our_version)

    if our_version == published_version:
        raise Exception(
            "You are attempting to republish version " + our_version)

    # sanity: check ChangeLog starts with our version
    changelog = open("CHANGELOG.rst", "r")
    found = False
    for line in changelog.readlines():
        if line.strip() == our_version:
            print("ChangeLog has an entry")
            found = True
            break
    changelog.close()
    if not found:
        raise Exception(
            "The ChangeLog does not appear to include comments on this release"
        )

    # Sanity check: is there a release tag
    tags = subprocess.check_output("hg tags".split())
    found = False
    looking_for = "Release " + our_version
    for line in tags.split("\n"):
        match = re.match(r"^(.*)\s+[0-9]+:[0-9a-f]+$", line)
        if match:
            tag = match.group(1).strip()
            if tag == looking_for:
                print("Found tag", tag)
                found = True
                break

    if not found:
        raise Exception(
            "Mercurial does not have the release tag: " + looking_for)

    status = subprocess.check_output(["hg", "status"])
    for line in status.split("\n"):
        if len(line) > 0:
            raise Exception("Uncommitted changes present")

    try:
        v = os.environ["RELEASE"]
        if v != "formic":
            raise KeyError()
    except KeyError:
        print("$RELEASE environment variable is not set")
        raise

    subprocess.check_call("python setup.py bdist_egg upload".split())
    subprocess.check_call("python setup.py sdist upload".split())
911222
def get_release_data(self):
        
        previous_package = self.get_previous_release()
        if previous_package:
            previous_version = previous_package.version
            previous_revision = previous_package.revision
        else:
            previous_version = None
            previous_revision = None

        if self.vcs is None:
            return dict(vcs="None",
                        previous_version=previous_version)

        revision = None
        with self.repo_operation():
            revision = self.vcs.get_current_revision()

        changelog = self.get_changelog()

        # truncate changelog - very large changelogs can cause package load
        # times to be very high, we don't want that
        maxlen = config.max_package_changelog_chars
        if maxlen and changelog and len(changelog) > maxlen + 3:
            changelog = changelog[:maxlen] + "..."

        return dict(vcs=self.vcs.name(),
                    revision=revision,
                    changelog=changelog,
                    previous_version=previous_version,
                    previous_revision=previous_revision)