~bzr-pqm/bzr/bzr.dev

6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
1
# Copyright (C) 2011 Canonical Ltd
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
17
"""Merge logic for po_merge plugin."""
18
6379.6.3 by Jelmer Vernooij
Use absolute_import.
19
from __future__ import absolute_import
20
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
21
from bzrlib import (
22
    config,
23
    merge,
24
    )
25
26
27
from bzrlib.lazy_import import lazy_import
28
lazy_import(globals(), """
29
import fnmatch
30
import subprocess
31
import tempfile
32
import sys
33
34
from bzrlib import (
35
    cmdline,
36
    osutils,
37
    trace,
38
    )
39
""")
40
41
6282.3.14 by Vincent Ladeuil
Use lazy registration for plugin options to set a good example.
42
command_option = config.Option(
43
        'po_merge.command',
44
        default='msgmerge -N "{other}" "{pot_file}" -C "{this}" -o "{result}"',
45
        help='''\
46
Command used to create a conflict-free .po file during merge.
47
48
The following parameters are provided by the hook:
49
``this`` is the ``.po`` file content before the merge in the current branch,
50
``other`` is the ``.po`` file content in the branch merged from,
51
``pot_file`` is the path to the ``.pot`` file corresponding to the ``.po``
52
file being merged.
53
``result`` is the path where ``msgmerge`` will output its result. The hook will
54
use the content of this file to produce the resulting ``.po`` file.
55
56
All paths are absolute.
57
''')
58
59
60
po_dirs_option = config.Option(
61
        'po_merge.po_dirs', default='po,debian/po',
62
        from_unicode=config.list_from_store,
63
        help='List of dirs containing .po files that the hook applies to.')
64
65
66
po_glob_option = config.Option(
67
        'po_merge.po_glob', default='*.po',
68
        help='Glob matching all ``.po`` files in one of ``po_merge.po_dirs``.')
69
70
pot_glob_option = config.Option(
71
        'po_merge.pot_glob', default='*.pot',
72
        help='Glob matching the ``.pot`` file in one of ``po_merge.po_dirs``.')
73
74
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
75
class PoMerger(merge.PerFileMerger):
76
    """Merge .po files."""
77
78
    def __init__(self, merger):
79
        super(merge.PerFileMerger, self).__init__(merger)
80
        # config options are cached locally until config files are (see
81
        # http://pad.lv/832042)
82
83
        # FIXME: We use the branch config as there is no tree config
84
        # -- vila 2011-11-23
85
        self.conf = merger.this_branch.get_config_stack()
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
86
        # Which dirs are targeted by the hook 
87
        self.po_dirs = self.conf.get('po_merge.po_dirs')
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
88
        # Which files are targeted by the hook 
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
89
        self.po_glob = self.conf.get('po_merge.po_glob')
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
90
        # Which .pot file should be used
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
91
        self.pot_glob = self.conf.get('po_merge.pot_glob')
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
92
        self.command = self.conf.get('po_merge.command', expand=False)
93
        # file_matches() will set the following for merge_text()
6282.3.10 by Vincent Ladeuil
Use an absolute path for {pot_file} so we don't have to care about the cwd for msgmerge.
94
        self.pot_file_abspath = None
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
95
        trace.mutter('PoMerger created')
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
96
97
    def file_matches(self, params):
98
        """Return True if merge_matching should be called on this file."""
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
99
        if not self.po_dirs or not self.command:
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
100
            # Return early if there is no options defined
101
            return False
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
102
        po_dir = None
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
103
        po_path = self.get_filepath(params, self.merger.this_tree)
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
104
        for po_dir in self.po_dirs:
105
            glob = osutils.pathjoin(po_dir, self.po_glob)
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
106
            if fnmatch.fnmatch(po_path, glob):
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
107
                trace.mutter('po %s matches: %s' % (po_path, glob))
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
108
                break
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
109
        else:
110
            trace.mutter('PoMerger did not match for %s and %s'
111
                         % (self.po_dirs, self.po_glob))
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
112
            return False
113
        # Do we have the corresponding .pot file
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
114
        for inv_entry in self.merger.this_tree.list_files(from_dir=po_dir,
115
                                                          recursive=False):
6282.3.10 by Vincent Ladeuil
Use an absolute path for {pot_file} so we don't have to care about the cwd for msgmerge.
116
            trace.mutter('inv_entry: %r' % (inv_entry,))
117
            pot_name, pot_file_id = inv_entry[0], inv_entry[3]
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
118
            if fnmatch.fnmatch(pot_name, self.pot_glob):
6282.3.10 by Vincent Ladeuil
Use an absolute path for {pot_file} so we don't have to care about the cwd for msgmerge.
119
                relpath = osutils.pathjoin(po_dir, pot_name)
120
                self.pot_file_abspath = self.merger.this_tree.abspath(relpath)
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
121
                # FIXME: I can't find an easy way to know if the .pot file has
122
                # conflicts *during* the merge itself. So either the actual
123
                # content on disk is fine and msgmerge will work OR it's not
124
                # and it will fail. Conversely, either the result is ok for the
125
                # user and he's happy OR the user needs to resolve the
126
                # conflicts in the .pot file and use remerge.
127
                # -- vila 2011-11-24
6282.3.8 by Vincent Ladeuil
We don't need select_po_file, we directly use the contents provided by merge for {this} and {other}.
128
                trace.mutter('will msgmerge %s using %s'
6282.3.10 by Vincent Ladeuil
Use an absolute path for {pot_file} so we don't have to care about the cwd for msgmerge.
129
                             % (po_path, self.pot_file_abspath))
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
130
                return True
131
        else:
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
132
            return False
133
134
    def _invoke(self, command):
6282.3.3 by Vincent Ladeuil
Change option scheme so users mainly have to deal with po_merge.po_dirs only.
135
        trace.mutter('Will msgmerge: %s' % (command,))
6282.3.10 by Vincent Ladeuil
Use an absolute path for {pot_file} so we don't have to care about the cwd for msgmerge.
136
        # We use only absolute paths so we don't care about the cwd
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
137
        proc = subprocess.Popen(cmdline.split(command),
138
                                stdout=subprocess.PIPE,
139
                                stderr=subprocess.PIPE,
140
                                stdin=subprocess.PIPE)
141
        out, err = proc.communicate()
142
        return proc.returncode, out, err
143
144
    def merge_matching(self, params):
145
        return self.merge_text(params)
146
147
    def merge_text(self, params):
148
        """Calls msgmerge when .po files conflict.
149
150
        This requires a valid .pot file to reconcile both sides.
151
        """
152
        # Create tmp files with the 'this' and 'other' content
153
        tmpdir = tempfile.mkdtemp(prefix='po_merge')
154
        env = {}
155
        env['this'] = osutils.pathjoin(tmpdir, 'this')
156
        env['other'] = osutils.pathjoin(tmpdir, 'other')
157
        env['result'] = osutils.pathjoin(tmpdir, 'result')
6282.3.10 by Vincent Ladeuil
Use an absolute path for {pot_file} so we don't have to care about the cwd for msgmerge.
158
        env['pot_file'] = self.pot_file_abspath
6282.3.1 by Vincent Ladeuil
First cut at a working plugin to avoid conflicts in .po files by shelling out to msgmerge.
159
        try:
160
            with osutils.open_file(env['this'], 'wb') as f:
161
                f.writelines(params.this_lines)
162
            with osutils.open_file(env['other'], 'wb') as f:
163
                f.writelines(params.other_lines)
164
            command = self.conf.expand_options(self.command, env)
165
            retcode, out, err = self._invoke(command)
166
            with osutils.open_file(env['result']) as f:
167
                # FIXME: To avoid the list() construct below which means the
168
                # whole 'result' file is kept in memory, there may be a way to
169
                # use an iterator that will close the file when it's done, but
170
                # there is still the issue of removing the tmp dir...
171
                # -- vila 2011-11-24
172
                return 'success', list(f.readlines())
173
        finally:
174
            osutils.rmtree(tmpdir)
175
        return 'not applicable', []