meson_templates.py 12.7 KB
Newer Older
1 2 3
#!/usr/bin/env python3
# __init__.py
#
4
# Copyright 2016 Patrick Griffis <tingping@tingping.se>
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import gi
import os
from os import path

from gi.repository import (
    Ide,
    Gio,
    GLib,
    GObject,
    GtkSource,
    Template,
)

_ = Ide.gettext

class LibraryTemplateProvider(GObject.Object, Ide.TemplateProvider):
    def do_get_project_templates(self):
36 37
        return [GnomeProjectTemplate(),
                LibraryProjectTemplate(),
38
                CLIProjectTemplate(),
39
                EmptyProjectTemplate()]
40

41 42 43 44 45 46 47 48 49 50 51 52
class MesonTemplateLocator(Template.TemplateLocator):
    license = None

    def empty(self):
        return Gio.MemoryInputStream()

    def do_locate(self, path):
        if path.startswith('license.'):
            filename = GLib.basename(path)
            manager = GtkSource.LanguageManager.get_default()
            language = manager.guess_language(filename, None)

53
            if self.license is None or language is None:
54 55 56 57 58 59 60 61 62 63 64
                return self.empty()

            header = Ide.language_format_header(language, self.license)
            gbytes = GLib.Bytes(header.encode())

            return Gio.MemoryInputStream.new_from_bytes(gbytes)

        return super().do_locate(self, path)


class MesonTemplate(Ide.TemplateBase, Ide.ProjectTemplate):
65
    def __init__(self, id, name, icon_name, description, languages, priority):
66 67 68 69 70 71
        super().__init__()
        self.id = id
        self.name = name
        self.icon_name = icon_name
        self.description = description
        self.languages = languages
72
        self.priority = priority
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
        self.locator = MesonTemplateLocator()

        self.props.locator = self.locator

    def do_get_id(self):
        return self.id

    def do_get_name(self):
        return self.name

    def do_get_icon_name(self):
        return self.icon_name

    def do_get_description(self):
        return self.description

    def do_get_languages(self):
        return self.languages

92 93 94
    def do_get_priority(self):
        return self.priority

95 96 97
    def do_expand_async(self, params, cancellable, callback, data):
        self.reset()

98
        task = Ide.Task.new(self, cancellable, callback)
99 100 101 102 103 104

        if 'language' in params:
            self.language = params['language'].get_string().lower()
        else:
            self.language = 'c'

105
        if self.language not in ('c', 'c♯', 'c++', 'javascript', 'python', 'vala'):
106
            task.return_error(GLib.Error('Language %s not supported' % self.language))
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
            return

        if 'versioning' in params:
            self.versioning = params['versioning'].get_string()
        else:
            self.versioning = ''

        if 'author' in params:
            author_name = params['author'].get_string()
        else:
            author_name = GLib.get_real_name()

        scope = Template.Scope.new()
        scope.get('template').assign_string(self.id)

        name = params['name'].get_string().lower()
123
        name_ = name.lower().replace('-', '_')
124 125
        scope.get('name').assign_string(name)
        scope.get('name_').assign_string(name_)
126 127
        scope.get('NAME').assign_string(name.upper().replace('-','_'))

128 129 130 131
        if 'app-id' in params:
            appid = params['app-id'].get_string()
        else:
            appid = 'org.example.App'
132 133 134
        appid_path = '/' + appid.replace('.', '/')
        scope.get('appid').assign_string(appid)
        scope.get('appid_path').assign_string(appid_path)
135

136 137 138 139 140 141 142 143 144 145 146 147 148
        prefix = name if not name.endswith('-glib') else name[:-5]
        PREFIX = prefix.upper().replace('-','_')
        prefix_ = prefix.lower().replace('-','_')
        PreFix = ''.join([word.capitalize() for word in prefix.lower().split('-')])

        scope.get('prefix').assign_string(prefix)
        scope.get('Prefix').assign_string(prefix.capitalize())
        scope.get('PreFix').assign_string(PreFix)
        scope.get('prefix_').assign_string(prefix_)
        scope.get('PREFIX').assign_string(PREFIX)


        enable_gnome = isinstance(self, GnomeProjectTemplate)
149
        scope.get('project_version').assign_string('0.1.0')
150 151 152
        scope.get('enable_i18n').assign_boolean(enable_gnome)
        scope.get('enable_gnome').assign_boolean(enable_gnome)
        scope.get('language').assign_string(self.language)
153 154
        scope.get('author').assign_string(author_name)

155
        # Just avoiding dealing with template bugs
156
        if self.language in ('c', 'c++'):
157
            ui_file = prefix + '-window.ui'
158 159
        elif self.language in ('c♯',):
            ui_file = ""
160 161 162 163 164 165 166
        else:
            ui_file = 'window.ui'
        scope.get('ui_file').assign_string(ui_file)

        exec_name = appid if self.language == 'javascript' else name
        scope.get('exec_name').assign_string(exec_name)

167
        modes = {
168 169
            'resources/src/hello.js.in': 0o750,
            'resources/src/hello.py.in': 0o750,
170
            'resources/src/application.in': 0o750,
171
            'resources/build-aux/meson/postinstall.py': 0o750,
172 173 174
        }

        expands = {
175 176 177 178
            'prefix': prefix,
            'appid': appid,
            'name_': name_,
            'name': name,
179
            'exec_name': exec_name,
180 181 182
        }

        files = {
183
            # Build files
184 185 186
            'resources/meson.build': 'meson.build',

        }
187
        self.prepare_files(files)
188

189 190 191
        # No explicit license == proprietary
        spdx_license = 'LicenseRef-proprietary'

192 193 194 195 196 197 198 199 200
        # https://spdx.org/licenses/
        LICENSE_TO_SPDX = {
            'agpl_3': 'AGPL-3.0-or-later',
            'gpl_3': 'GPL-3.0-or-later',
            'lgpl_2_1': 'LGPL-2.1-or-later',
            'lgpl_3': 'LGPL-3.0-or-later',
            'mit_x11': 'MIT',
        }

201 202 203 204 205 206 207 208
        if 'license_full' in params:
            license_full_path = params['license_full'].get_string()
            files[license_full_path] = 'COPYING'

        if 'license_short' in params:
            license_short_path = params['license_short'].get_string()
            license_base = Gio.resources_lookup_data(license_short_path[11:], 0).get_data().decode()
            self.locator.license = license_base
209 210 211 212
            license_name = license_short_path.rsplit('/', 1)[1]
            spdx_license = LICENSE_TO_SPDX.get(license_name, '')

        scope.get('project_license').assign_string(spdx_license)
213 214 215 216 217 218 219 220 221 222

        if 'path' in params:
            dir_path = params['path'].get_string()
        else:
            dir_path = name
        directory = Gio.File.new_for_path(dir_path)
        scope.get('project_path').assign_string(directory.get_path())

        for src, dst in files.items():
            destination = directory.get_child(dst % expands)
223
            if src.startswith('resource://'):
224 225
                self.add_resource(src[11:], destination, scope, modes.get(src, 0))
            else:
226
                path = os.path.join('/plugins/meson_templates', src)
227
                self.add_resource(path, destination, scope, modes.get(src, 0))
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

        self.expand_all_async(cancellable, self.expand_all_cb, task)

    def do_expand_finish(self, result):
        return result.propagate_boolean()

    def expand_all_cb(self, obj, result, task):
        try:
            self.expand_all_finish(result)
            task.return_boolean(True)
        except Exception as exc:
            if isinstance(exc, GLib.Error):
                task.return_error(exc)
            else:
                task.return_error(GLib.Error(repr(exc)))


245
class GnomeProjectTemplate(MesonTemplate):
246 247
    def __init__(self):
        super().__init__(
248 249 250 251
            'gnome-app',
            _('GNOME Application'),
            'pattern-gnome',
            _('Create a new GNOME application'),
252 253
            ['C', 'C++', 'C♯', 'Python', 'JavaScript', 'Vala'],
            0
254 255 256 257 258 259 260 261 262
         )

    def prepare_files(self, files):
        # Shared files
        files['resources/flatpak.json'] = '%(appid)s.json'
        files['resources/data/hello.desktop.in'] = 'data/%(appid)s.desktop.in'
        files['resources/data/hello.appdata.xml.in'] = 'data/%(appid)s.appdata.xml.in'
        files['resources/data/hello.gschema.xml'] = 'data/%(appid)s.gschema.xml'
        files['resources/data/meson.build'] = 'data/meson.build'
263
        files['resources/build-aux/meson/postinstall.py'] = 'build-aux/meson/postinstall.py'
264 265 266 267 268 269 270 271 272 273 274 275
        files['resources/po/LINGUAS'] = 'po/LINGUAS'
        files['resources/po/meson.build'] = 'po/meson.build'
        files['resources/po/POTFILES'] = 'po/POTFILES'
        window_ui_name = 'src/window.ui'
        resource_name = 'src/%(prefix)s.gresource.xml'
        meson_file = 'resources/src/meson-c-vala.build'

        if self.language == 'c':
            files['resources/src/main.c'] = 'src/main.c'
            files['resources/src/window.c'] = 'src/%(prefix)s-window.c'
            files['resources/src/window.h'] = 'src/%(prefix)s-window.h'
            window_ui_name = 'src/%(prefix)s-window.ui'
276 277 278 279 280
        elif self.language == 'c++':
            files['resources/src/main.cpp'] = 'src/main.cpp'
            files['resources/src/window.cpp'] = 'src/%(prefix)s-window.cpp'
            files['resources/src/window.hpp'] = 'src/%(prefix)s-window.h'
            window_ui_name = 'src/%(prefix)s-window.ui'
281 282 283
        elif self.language == 'c♯':
            files['resources/src/main.cs'] = 'src/main.cs'
            files['resources/src/application.in'] = 'src/%(exec_name)s.in'
284
            files['resources/flatpak-gtksharp.json.tmpl'] = '%(appid)s.json'
285 286 287
            meson_file = 'resources/src/meson-cs.build'
            resource_name = None
            window_ui_name = None
288 289 290 291
        elif self.language == 'vala':
            files['resources/src/main.vala'] = 'src/main.vala'
            files['resources/src/window.vala'] = 'src/window.vala'
        elif self.language == 'javascript':
292
            files['resources/src/main.js.tmpl'] = 'src/main.js'
293
            files['resources/src/hello.js.in'] = 'src/%(appid)s.in'
294
            files['resources/src/window.js.tmpl'] = 'src/window.js'
295 296 297 298 299 300 301 302 303 304
            files['resources/src/hello.src.gresource.xml'] = 'src/%(appid)s.src.gresource.xml'
            resource_name = 'src/%(appid)s.data.gresource.xml'
            meson_file = 'resources/src/meson-js.build'
        elif self.language == 'python':
            files['resources/src/hello.py.in'] = 'src/%(name)s.in'
            files['resources/src/__init__.py'] = 'src/__init__.py'
            files['resources/src/window.py'] = 'src/window.py'
            files['resources/src/main.py'] = 'src/main.py'
            meson_file = 'resources/src/meson-py.build'

305 306 307 308 309
        if resource_name:
            files['resources/src/hello.gresource.xml'] = resource_name
        if window_ui_name:
            files['resources/src/window.ui'] = window_ui_name

310 311 312 313 314 315 316 317
        files[meson_file] = 'src/meson.build'


class LibraryProjectTemplate(MesonTemplate):
    def __init__(self):
        super().__init__(
            'shared-library',
            _("Shared Library"),
318
            'pattern-library',
319
            _("Create a new project with a shared library"),
320 321
            ['C'],
            100
322 323
         )

324 325 326 327 328 329
    def prepare_files(self, files):
        if self.language == 'c':
            files['resources/src/meson-clib.build'] = 'src/meson.build'
            files['resources/src/hello.h'] = 'src/%(name)s.h'
            files['resources/src/hello-version.h.in'] = 'src/%(prefix)s-version.h.in'

330

331 332 333 334 335
class EmptyProjectTemplate(MesonTemplate):
    def __init__(self):
        super().__init__(
            'empty',
            _('Empty Project'),
336
            'pattern-cli',
337
            _('Create a new empty project'),
338
            ['C', 'C++', 'C♯', 'JavaScript', 'Python', 'Vala'],
339
            200
340
         )
341 342 343

    def prepare_files(self, files):
        files['resources/src/meson-empty.build'] = 'src/meson.build'
344

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

class CLIProjectTemplate(MesonTemplate):
    def __init__(self):
        super().__init__(
            'cli',
            _('Command Line Tool'),
            'pattern-cli',
            _('Create a new command line project'),
            ['C', 'Vala'],
            200
         )

    def prepare_files(self, files):
        files['resources/src/meson-cli.build'] = 'src/meson.build'

        if self.language == 'c':
            files['resources/src/main-cli.c'] = 'src/main.c'
        elif self.language == 'vala':
            files['resources/src/main-cli.vala'] = 'src/main.vala'