maint 14 KB
Newer Older
1
#!/usr/bin/env python3
2 3 4 5

import collections
import datetime
import os
6
import re
7
import subprocess
8
import urllib.parse
9

10
import click
11 12
import keyring
import requests
13
from jinja2 import Environment
14 15 16 17 18

import meld.conf

PO_DIR = "po"
HELP_DIR = "help"
19
RELEASE_BRANCH_RE = r'%s-\d+-\d+' % meld.conf.__package__
20
VERSION_RE = r'__version__\s*=\s*"(?P<version>.*)"'
21
UPLOAD_SERVER = 'master.gnome.org'
22 23
GITLAB_API_BASE = 'https://gitlab.gnome.org/api/v4'
GITLAB_PROJECT_ID = 'GNOME/meld'
24 25 26 27 28 29 30 31 32 33 34 35 36 37

NEWS_TEMPLATE = """
{{ [date, app, version]|join(' ') }}
{{ '=' * [date, app, version]|join(' ')|length }}

  Features:


  Fixes:
{% for commit in commits%}
   * {{ commit }}
{%- endfor %}

  Translations:
38 39
{% for translator in translator_langs|sort %}
   * {{ translator }} ({{translator_langs[translator]|sort|join(', ')}})
40 41 42 43
{%- endfor %}

"""

44 45
EMAIL_TEMPLATE = """
{{ app|title }} {{version}} has been released, and is now available at:
46
  https://download.gnome.org/sources/meld/{{ version|minor_version }}/{{ app }}-{{ version }}.tar.xz
47
{%- if features %}
48 49 50 51 52 53 54


Features
--------
{% for feature in features %}
 {{ feature }}
{%- endfor %}
55
{%- endif %}
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79


Fixes
-----
{% for fix in fixes %}
 {{ fix }}
{%- endfor %}


Translations
------------
{% for translator in translators %}
 {{ translator }}
{%- endfor %}


What is Meld?
-------------

Meld is a visual diff and merge tool. It lets you compare two or three files,
and updates the comparisons while you edit them in-place. You can also compare
folders, launching comparisons of individual files as desired. Last but by no
means least, Meld lets you work with your current changes in a wide variety of
version control systems, including Git, Bazaar, Mercurial and Subversion.
80

81 82 83 84 85 86 87 88
"""


MARKDOWN_TEMPLATE = """
<!--
{{ [date, app, version]|join(' ') }}
{{ '=' * [date, app, version]|join(' ')|length }}
-->
89
{%- if features %}
90 91 92 93 94 95

Features
--------
{% for feature in features %}
{{ feature }}
{%- endfor %}
96
{%- endif %}
97 98 99 100 101 102 103 104 105 106 107 108

Fixes
-----
{% for fix in fixes %}
{{ fix }}
{%- endfor %}

Translations
------------
{% for translator in translators %}
{{ translator }}
{%- endfor %}
109

110 111
"""

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

def get_last_release_tag():
    cmd = ['git', 'describe', '--abbrev=0', '--tags']
    tag_name = subprocess.check_output(cmd).strip().decode('utf-8')
    try:
        version = [int(v) for v in tag_name.split('.')]
        if len(version) != 3:
            raise ValueError()
    except ValueError:
        raise ValueError("Couldn't parse tag name %s" % tag_name)
    return tag_name


def get_translation_commits(folder):
    last_release = get_last_release_tag()
    revspec = "%s..HEAD" % last_release
    cmd = ['git', 'log', '--pretty=format:%an', '--name-only', revspec,
           '--', folder]
    name_files = subprocess.check_output(cmd).strip().decode('utf-8')
    if not name_files:
        return []
    commits = name_files.split('\n\n')
    commits = [(c.split('\n')[0], c.split('\n')[1:]) for c in commits]
    return commits


def get_translator_langs(folders=[PO_DIR, HELP_DIR]):

    def get_lang(path):
        filename = os.path.basename(path)
        if not filename.endswith('.po'):
            return None
        return filename[:-3]

    translation_commits = []
    for folder in folders:
        translation_commits.extend(get_translation_commits(folder))

    author_map = collections.defaultdict(set)
    for author, langs in translation_commits:
        langs = [get_lang(lang) for lang in langs if get_lang(lang)]
        author_map[author] |= set(langs)

    return author_map


def get_non_translation_commits():
    last_release = get_last_release_tag()
    revspec = "%s..HEAD" % last_release
161 162 163 164 165 166 167
    cmd = [
        'git', 'log', '--pretty=format:%s (%an)', revspec,
        # Exclude commits that only cover the po/ or help/ folders,
        # except commits in help/C. Basically, we want to separate
        # translation-only commits from everything else.
        '--', '.', ":!po/", ':(glob,exclude)help/[!C]*/**',
    ]
168 169 170 171
    commits = subprocess.check_output(cmd).strip().splitlines()
    return [c.decode('utf-8') for c in commits]


172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
def get_last_news_entry():
    cmd = ['git', 'log', '--pretty=format:', '-p', '-1', 'NEWS']
    lines = subprocess.check_output(cmd).strip().decode('utf-8').splitlines()
    lines = [l[1:] for l in lines if (l and l[0] in ('+', '-')) and
             (len(l) < 2 or l[1] not in ('+', '-'))]
    return "\n".join(lines)


def parse_news_entry(news):
    features, fixes, translators = [], [], []
    section = None
    sections = {
        'Features': features,
        'Fixes': fixes,
        'Translations': translators,
    }
    for line in news.splitlines():
        if line.strip(' :') in sections:
            section = line.strip(' :')
            continue
        if not section or not line.strip():
            continue
        sections[section].append(line)

    def reformat(section):
197 198 199
        if not section:
            return section

200 201 202 203 204 205 206 207 208 209 210 211 212
        def space_prefix(s):
            for i in range(1, len(s)):
                if not s[:i].isspace():
                    break
            return i - 1

        indent = min(space_prefix(l) for l in section)
        return [l[indent:] for l in section]

    return reformat(features), reformat(fixes), reformat(translators)


def make_env():
213

214 215 216 217 218 219 220 221 222 223 224 225
    def minor_version(version):
        return '.'.join(version.split('.')[:2])

    jinja_env = Environment()
    jinja_env.filters['minor_version'] = minor_version
    return jinja_env


def get_tokens():
    news = get_last_news_entry()
    features, fixes, translators = parse_news_entry(news)
    return {
226 227 228
        'date': datetime.date.today().isoformat(),
        'app': meld.conf.__package__,
        'version': meld.conf.__version__,
229 230 231 232
        'translator_langs': get_translator_langs(),
        'features': features,
        'fixes': fixes,
        'translators': translators,
233 234 235
        'commits': get_non_translation_commits(),
    }

236

237 238 239 240
def render_template(template):
    tokens = get_tokens()
    jinja_env = make_env()
    template = jinja_env.from_string(template)
241 242 243
    return(template.render(tokens))


244
def call_with_output(
245
        cmd, stdin_text=None, echo_stdout=True, abort_on_fail=True,
246
        timeout=30):
247 248
    PIPE = subprocess.PIPE
    with subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
249
        stdout, stderr = proc.communicate(stdin_text, timeout=timeout)
250 251 252 253
    if stdout and echo_stdout:
        click.echo('\n' + stdout.decode('utf-8'))
    if stderr or proc.returncode:
        click.secho('\n' + stderr.decode('utf-8'), fg='red')
254
    if abort_on_fail and proc.returncode:
255
        raise click.Abort()
256
    return proc.returncode
257 258


259 260 261 262 263 264 265 266 267 268
def check_release_branch():
    cmd = ['git', 'rev-parse', '--abbrev-ref', 'HEAD']
    branch = subprocess.check_output(cmd).strip().decode('utf-8')
    if branch != 'master' and not re.match(RELEASE_BRANCH_RE, branch):
        click.echo(
            '\nBranch "%s" doesn\'t appear to be a release branch.\n' % branch)
        click.confirm('Are you sure you wish to continue?', abort=True)
    return branch


269 270 271 272 273 274
def pull():
    check_release_branch()
    cmd = ['git', 'pull', '--rebase']
    call_with_output(cmd, timeout=None)


275
def commit(message=None):
276 277 278 279 280 281 282
    cmd = ['git', 'diff', 'HEAD']
    call_with_output(cmd, echo_stdout=True)
    confirm = click.confirm('\nCommit this change?', default=True)
    if not confirm:
        return

    cmd = ['git', 'commit', '-a']
283
    if message:
284 285
        cmd.append('-m')
        cmd.append(message)
286 287 288
    call_with_output(cmd, timeout=None)


289 290
def push():
    branch = check_release_branch()
Kai Willadsen's avatar
Kai Willadsen committed
291
    cmd = ['git', 'log', 'origin/%s..%s' % (branch, branch)]
292 293 294 295 296 297
    call_with_output(cmd, echo_stdout=True)

    confirm = click.confirm('\nPush these commits?', default=True)
    if not confirm:
        return

298
    cmd = ['git', 'push']
299 300 301
    call_with_output(cmd, echo_stdout=True)


302 303 304 305 306 307 308 309 310 311 312 313
def gitlab_release_tag(tag):
    auth_token = keyring.get_password('gitlab-api', GITLAB_PROJECT_ID)
    if not auth_token:
        raise click.ClickException(
            "No password in keychain for {id}\n\n"
            "Set password using the Python `keyring` package. "
            "From the command line:\n"
            "  $ keyring set gitlab-api {id}\n"
            "and enter your secret token from the Gitlab UI.\n".format(
                id=GITLAB_PROJECT_ID)
        )

314
    cmd = ['git', 'tag', '-l', "--format=%(contents)", tag]
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    description = subprocess.check_output(cmd).decode('utf-8')

    endpoint = '{base}/projects/{id}/repository/tags/{tag_name}/release'
    release_url = endpoint.format(
        base=GITLAB_API_BASE,
        id=urllib.parse.quote_plus(GITLAB_PROJECT_ID),
        tag_name=tag,
    )
    release_data = {
        "tag_name": tag,
        "description": description
    }

    # TODO: Should probably sanity-check that it's not already a
    # release tag.

331
    response = requests.post(
332
        release_url,
333
        json=release_data,
334 335 336 337
        headers={
            'Private-Token': auth_token,
        },
    )
338 339 340 341 342
    try:
        response.raise_for_status()
    except Exception as e:
        click.secho(
            'Error making release: {}\n{}'.format(e, response.text), fg='red')
343 344


345 346 347
@click.group()
def cli():
    pass
348

Kai Willadsen's avatar
Kai Willadsen committed
349

350 351
@cli.command()
def test():
352
    cmd = ['py.test-3', 'test/']
Kai Willadsen's avatar
Kai Willadsen committed
353 354
    call_with_output(cmd, echo_stdout=True)

355

356 357
@cli.command()
def news():
358
    rendered = render_template(NEWS_TEMPLATE)
359 360 361 362 363 364 365 366 367
    with open('NEWS', 'r') as f:
        current_news = f.read()

    new_news = rendered + current_news
    with open('NEWS', 'w') as f:
        f.write(new_news)

    message = click.edit(filename='NEWS')
    return message
368 369


370 371
def write_somewhere(filename, output):
    if filename and os.path.exists(filename):
372 373 374 375
        overwrite = click.confirm(
            'File "%s" already exists. Overwrite?' % filename, abort=True)
        if not overwrite:
            raise click.Abort()
376 377 378
    if filename:
        with open(filename, 'w') as f:
            f.write(output)
379
        click.echo('Wrote %s' % filename)
380 381 382 383
    else:
        click.echo(output)


384
@cli.command()
385 386 387
@click.argument('filename', type=click.Path(), default=None, required=False)
def email(filename):
    write_somewhere(filename, render_template(EMAIL_TEMPLATE))
388 389 390


@cli.command()
391 392 393
@click.argument('filename', type=click.Path(), default=None, required=False)
def markdown(filename):
    write_somewhere(filename, render_template(MARKDOWN_TEMPLATE))
394 395 396 397 398 399 400 401


@cli.command()
def dist():
    archive = '%s-%s.tar.bz2' % (meld.conf.__package__, meld.conf.__version__)
    dist_archive_path = os.path.abspath(os.path.join('dist', archive))
    if os.path.exists(dist_archive_path):
        click.echo('Replacing %s...' % dist_archive_path)
402
    cmd = ['python3', 'setup.py', 'sdist', '--formats=bztar']
403 404
    call_with_output(cmd, echo_stdout=False)
    if not os.path.exists(dist_archive_path):
405 406
        click.echo('Failed to create archive file %s' % dist_archive_path)
        raise click.Abort()
407 408 409 410 411 412 413 414 415 416 417 418
    return dist_archive_path


@cli.command()
def tag():
    last_release = get_last_release_tag()
    click.echo('\nLast release tag was: ', nl=False)
    click.secho(last_release, fg='green', bold=True)
    click.echo('New release tag will be: ', nl=False)
    click.secho(meld.conf.__version__, fg='green', bold=True)
    click.confirm('\nTag this release?', default=True, abort=True)

419
    news_text = get_last_news_entry().encode('utf-8')
420 421 422 423 424 425 426 427 428 429 430
    # FIXME: Should be signing tags
    cmd = ['git', 'tag', '-a', '--file=-', meld.conf.__version__]
    call_with_output(cmd, news_text)
    click.echo('Tagged %s' % meld.conf.__version__)

    cmd = ['git', 'show', '-s', meld.conf.__version__]
    call_with_output(cmd, echo_stdout=True)
    confirm = click.confirm('\nPush this tag?', default=True)
    if not confirm:
        return

431
    cmd = ['git', 'push', 'origin', meld.conf.__version__]
432 433 434
    call_with_output(cmd, echo_stdout=True)


435 436
@cli.command('gitlab-release')
def gitlab_release():
437 438 439 440 441 442 443 444 445
    last_release = get_last_release_tag()
    confirm = click.confirm(
        'Annotate {} as a Gitlab release?'.format(last_release), default=True)
    if not confirm:
        return

    gitlab_release_tag(last_release)


446 447 448
@cli.command()
@click.argument('path', type=click.Path(exists=True))
def upload(path):
449 450 451 452 453
    confirm = click.confirm(
        '\nUpload %s to %s?' % (path, UPLOAD_SERVER), default=True,
        abort=False)
    if not confirm:
        return
454
    cmd = ['scp', path, UPLOAD_SERVER + ':']
455
    call_with_output(cmd, timeout=120)
456 457


458
@cli.command('version-bump')
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
def version_bump():
    with open(meld.conf.__file__) as f:
        conf_data = f.read().splitlines()

    for i, line in enumerate(conf_data):
        if line.startswith('__version__'):
            match = re.match(VERSION_RE, line)
            version = match.group('version')
            if version != meld.conf.__version__:
                continue
            version_line = i
            break
    else:
        click.echo('Couldn\'t determine version from %s' % meld.conf.__file__)
        raise click.Abort()

    click.echo('Current version is: %s' % meld.conf.__version__)
    default_version = meld.conf.__version__.split('.')
    default_version[-1] = str(int(default_version[-1]) + 1)
    default_version = '.'.join(default_version)
    new_version = click.prompt('Enter new version', default=default_version)

    conf_data[version_line] = '__version__ = "%s"' % new_version
    with open(meld.conf.__file__, 'w') as f:
        f.write('\n'.join(conf_data) + '\n')


486
@cli.command('release')
487 488
@click.pass_context
def make_release(ctx):
489 490 491 492 493 494
    pull()
    ctx.forward(news)
    commit(message='Update NEWS')
    push()
    archive_path = ctx.forward(dist)
    ctx.forward(tag)
495
    ctx.forward(gitlab_release)
496 497 498
    file_prefix = '%s-%s' % (meld.conf.__package__, meld.conf.__version__)
    ctx.forward(email, filename=file_prefix + '-email')
    ctx.forward(markdown, filename=file_prefix + '.md')
499
    ctx.forward(version_bump)
500
    commit(message='Post-release version bump')
501
    push()
502

503 504
    ctx.forward(upload, path=archive_path)

505 506 507 508 509
    # TODO: ssh in and run ftpadmin install
    click.echo('\nNow run:')
    click.echo('ssh %s' % UPLOAD_SERVER)
    click.echo('ftpadmin install %s' % os.path.basename(archive_path))

510 511

if __name__ == '__main__':
512 513
    # FIXME: Should include sanity check that we're at the top level of the
    # project
514
    cli()