This file is indexed.

/usr/lib/python3/dist-packages/plainbox/impl/commands/startprovider.py is in python3-plainbox 0.5.3-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  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
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
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
161
162
163
164
165
166
167
168
169
170
171
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# This file is part of Checkbox.
#
# Copyright 2013 Canonical Ltd.
# Written by:
#   Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# Checkbox 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.
#
# Checkbox 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 Checkbox.  If not, see <http://www.gnu.org/licenses/>.

"""
:mod:`plainbox.impl.commands.startprovider` -- startprovider sub-command
========================================================================
"""
import inspect
import logging
import os
import re

from plainbox.i18n import docstring
from plainbox.i18n import gettext as _
from plainbox.i18n import gettext_noop as N_
from plainbox.impl.commands import PlainBoxCommand
from plainbox.impl.secure.providers.v1 import IQNValidator

logger = logging.getLogger("plainbox.commands.startprovider")


class IQN(str):
    """
    A string subclass that validates values with the IQNValidator
    """

    _validator = IQNValidator()

    def __new__(mcls, value):
        problem = mcls._validator(None, value)
        if problem:
            raise ValueError(problem)
        return super().__new__(mcls, value)


class SomethingInTheWay(Exception):
    """
    Exception raised if a file or directory that we were hoping to create
    already exists. To avoid overwriting data this exception is raised instead
    """

    def __init__(self, filename):
        self.filename = filename

    def __str__(self):
        return _("refusing to overwrite {!a}").format(self.filename)


class File:
    """
    A helper class to create files from a text template.

    The generated file can have some custom content interpolated with the
    python format syntax. All keyword arguments passed to :meth:`instantiate()`
    are used as formatting variables.

    The generated file can be placed in a parent directory (just plain
    directory name), not the :class:`Directory` class. The name undergoes the
    same template expansion as the contents.

    The generated file can be marked as executable, if applicable for the given
    platform.
    """

    def __init__(self, name, parent=None, executable=False, full_text=""):
        self.name = name
        self.parent = parent
        self.executable = executable
        self.full_text = inspect.cleandoc(full_text)

    def instantiate(self, root, **kwargs):
        if self.parent:
            filename = os.path.join(
                root, self.parent, self.name.format(**kwargs))
        else:
            filename = os.path.join(root, self.name.format(**kwargs))
        if os.path.exists(filename):
            raise SomethingInTheWay(filename)
        with open(filename, "wt", encoding="UTF-8") as stream:
            content = self.full_text.format(**kwargs)
            stream.write(content)
        if self.executable:
            os.chmod(filename, 0o775)


class Directory:
    """
    A helper class to create a directory from a simple template.

    The generated directory can be placed in a parent directory (just plain
    directory name), not the :class:`Directory` class. The name undergoes the
    same template expansion as the contents.
    """

    def __init__(self, name):
        self.name = name

    def __enter__(self):
        return self.name

    def __exit__(self, *args):
        pass

    def instantiate(self, root, **kwargs):
        dirname = os.path.join(root, self.name.format(**kwargs))
        if os.path.exists(dirname):
            raise SomethingInTheWay(dirname)
        os.mkdir(dirname)


class Skeleton(Directory):
    """
    A helper class to create a directory with other files and directories.

    The class may define the ``things`` attribute (a list). All items of that
    list are instantiated, just like File and Directory can.
    """

    things = []

    def instantiate(self, root, **kwargs):
        super().instantiate(root, **kwargs)
        for thing in self.things:
            thing.instantiate(
                os.path.join(root, self.name.format(**kwargs)), **kwargs)


class ProviderSkeleton(Skeleton):
    """
    A skeleton with various content created for the startprovider command.
    """

    things = []

    jobs_dir = Directory("jobs")
    things.append(jobs_dir)

    whitelists_dir = Directory("whitelists")
    things.append(whitelists_dir)

    data_dir = Directory("data")
    things.append(data_dir)

    bin_dir = Directory("bin")
    things.append(bin_dir)

    po_dir = Directory("po")
    things.append(po_dir)

    things.append(File("README.md", full_text="""
         Skeleton for a new PlainBox provider
         ====================================

         This is a skeleton PlainBox provider that was generated using
         ``plainbox startprovider ...``.

         It is just the starting point, there is nothing here of value to you
         yet. If you know how this works then just remove this file along with
         other example content and start working on your new tests,
         otherwise, read on.

         Inside the ``jobs/`` directory you will find several files that define
         a number of "jobs" (more than one job per file actually). A job, in
         PlainBox parlance, is the smallest piece of executable test code. Each
         job has a name and a number of other attributes.

         Jobs can be arranged in lists, test plans if you will that are known
         as "whitelists". Those are defined in the ``whitelists/`` directory,
         this time one per file. You can create as many whitelists as you need,
         referring to arbitrary subsets of your jobs.

         Then there are the ``bin/`` and ``data/`` directories. Those are
         entirely for custom content you may need. You can put arbitrary
         executables in ``bin/``, and those will be available to your job
         definitions. Similarly you can keep any data your jobs might need
         inside the ``data/`` directory. Referring to that directory at runtime
         is a little bit trickier but one of the examples generated in this
         skeleton shows how to do that.

         Lastly there is the ``manage.py`` script. It requires python3 to run.
         It depends on the python3-plainbox Debian package (or just the
         PlainBox 0.5 upstream package) installed. This script can automate and
         simplify a number of tasks that you will want to do as a test
         developer.

         Run ``./manage.py --help`` to see what sub-commands are available. You
         can additionally pass ``--help`` to each sub command, for example
         ``./manage.py install --help`` will print the description of the
         install command and all the arguments it supports.

         That is it for now. You should check out the official documentation
         for test authors at
         http://plainbox.readthedocs.org/en/latest/author/index.html

         If you find bugs or would like to see additional features developed
         you can file bugs on the parent project page:
         https://bugs.launchpad.net/checkbox/+filebug
         """))

    with jobs_dir as parent:

        things.append(File("examples-trivial.txt", parent, full_text="""
             # Two example jobs, both using the 'shell' "plugin". See the
             # documentation for examples of other test cases including
             # interactive tests, "resource" tests and a few other types.
             #
             # The summary and description keys are prefixed with _
             # to indicate that they can be translated.
             #
             # http://plainbox.rtfd.org/en/latest/author/jobs.html
             id: examples/trivial/always-pass
             _summary: A test that always passes
             _description:
                A test that always passes
                .
                This simple test will always succeed, assuming your
                platform has a 'true' command that returns 0.
             plugin: shell
             estimated_duration: 0.01
             command: true

             id: examples/trivial/always-fail
             _summary: A test that always fails
             _description:
                A test that always fails
                .
                This simple test will always fail, assuming your
                platform has a 'false' command that returns 1.
             plugin: shell
             estimated_duration: 0.01
             command: false
             """))

        things.append(File("examples-normal.txt", parent, full_text="""
             id: examples/normal/data-access
             _summary: Example job using provider-specific data
             _description:
                This test illustrates that custom data can be accessed using
                the $PLAINBOX_PROVIDER_DATA environment variable. It points to
                the absolute path of the data directory of the provider.
             plugin: shell
             estimated_duration: 0.01
             command:
                test "$(cat $PLAINBOX_PROVIDER_DATA/example.dat)" = "DATA"

             id: examples/normal/bin-access
             _summary: Example job using provider-specific executable
             _description:
                This test illustrates that custom executables can be accessed
                directly, if placed in the bin/ directory of the provider.
                .
                Those are made available in the PATH, at runtime. This job
                succeeds because the custom-executable script returns 0.
             plugin: shell
             estimated_duration: 0.01
             command: custom-executable

             id: examples/normal/info-collection
             _summary: Example job attaching command output to results
             _description:
                This test illustrates that output of a job may be collected
                for analysis using the plugin type ``attachment``
                .
                Attachment jobs may fail and behave almost the same as shell
                jobs (exit status decides their outcome)
                .
                The output is saved but, depending on how tests are how results
                are handled, may not be displayed. You can save attachments
                using, for example, the JSON test result exporter, like this:
                ``plainbox run -f json -p with-attachments``
             plugin: attachment
             estimated_duration: 0.01
             command: cat /proc/cpuinfo
             """))

        things.append(File("examples-intermediate.txt", parent, full_text="""
             id: examples/intermediate/dependency-target
             _summary: Example job that some other job depends on
             _description:
                This test illustrates how a job can be a dependency of another
                job. The dependency graph can be arbitrarily complex, it just
                cannot have any cycles. PlainBox will discover various problems
                related to dependencies, including cyclic dependencies and
                jobs that are depended upon, without a definition.
                .
                This job simply "passes" all the time but realistic examples
                may include multi-stage manipulation (detect a device, set it
                up, perform some automatic and some manual tests and summarise
                the results, for example)
             plugin: shell
             command: true
             estimated_duration: 0.01

             id: examples/intermediate/dependency-source
             _summary: Example job that depends on another job
             _description:
                This test illustrates how a job can depend on another job.
                .
                If you run this example unmodified (selecting just this job)
                you will see that PlainBox will automatically run the
                'dependency-target' job before attempting to run this one.
                This will happen, even if you explicitly order the jobs
                incorrectly.
                .
                If you edit the 'dependency-target' job to run 'false' instead
                of 'true' and rerun this job you will see that it automatically
                fails without being started. This is because of a rule which
                automatically fails any job that has a failed dependency.
             plugin: shell
             command: true
             depends: examples/intermediate/dependency-target
             estimated_duration: 0.01

             # TODO: this should be possible:
             # name: examples/intermediate/detected-device
             # resource-object: examples.intermediate.detected_device
             id: detected_device
             _summary: Example job producing structured resource data
             _description:
                This job illustrates that not all jobs are designed to be a
                "test". PlainBox has a system of the so-called resources.
                .
                Technically a resource is a list of records with named fields.
                Any program that prints RFC822-like output can be considered a
                valid resource. Here a hypothetical resource program has
                detected (fake) two devices which are represented as records
                with the field ``device``.
                .
                Resources are ran on demand, their output parsed and stored.
                All resources are made available to jobs that use resource
                programs. See the next job for an example of how that can be
                useful.
             plugin: resource
             command:
                echo "type: WEBCAM"
                echo ""
                echo "type: WIFI"
             estimated_duration: 0.03

             id: examples/intermediate/test-webcam
             _summary: Example job depending on structured resource
             _description:
                This test illustrates two concepts. It is the first test that
                uses manual jobs (totally not automated test type). It also
                uses a resource dependency, via a resource program, to limit
                this test only on a machine that has a hypothetical webcam.
                .
                If you run this example unmodified (selecting just this job)
                you will see that PlainBox will automatically run the
                'detected_device' job before attempting to run this one. This
                will happen, even if you explicitly order the jobs incorrectly.
                .
                If you edit the resource job to not print information about the
                hypothetical WEBCAM device (just remove that line) and rerun
                this job you will see that it automatically gets skipped
                without being started. This is because of a rule which
                automatically skips any job that has unmet requirement.
                .
                Resources are documented in detail here:
                http://plainbox.rtfd.org/en/latest/search.html?q=resources
                Please look at the ``Resources`` chapter there (it may move so
                a search link is more reliable)
             plugin: manual
             requires:
                 detected_device.type == "WEBCAM"
             estimated_duration: 30
             """))

    with whitelists_dir as parent:

        things.append(File("trivial.whitelist", parent, full_text="""
             # select two trivial jobs by directly selecting their names
             examples/trivial/always-pass
             examples/trivial/always-fail
             """))

        things.append(File("normal.whitelist", parent, full_text="""
             # use regular expression to select all normal jobs
             examples/normal/.*
             """))

    with po_dir as parent:

        things.append(File("POTFILES.in", parent, full_text="""
            [encoding: UTF-8]
            [type: gettext/rfc822deb] jobs/examples-trivial.txt
            [type: gettext/rfc822deb] jobs/examples-normal.txt
            [type: gettext/rfc822deb] jobs/examples-intermediate.txt
            manage.py
        """))

    with data_dir as parent:

        things.append(File("README.md", parent, full_text="""
             Container for arbitrary data needed by tests
             ============================================

             You can refer to files from this directory, in your scripts, using
             the $PLAINBOX\\_PROVIDER\\_DATA environment variable. See the job
             examples/data-access for details.

             You should delete this file as anything here is automatically
             distributed in the source tarball or installed.
             """))

        things.append(File("example.dat", parent, full_text="DATA"))

    with bin_dir as parent:

        things.append(File("README.md", parent, full_text="""
             Container for arbitrary executables needed by tests
             ===================================================

             You can execute files from this directory without any additional
             setup, they are automatically added to the PATH of the executing
             job examples/bin-access for details.

             You should delete this file as anything here is automatically
             distributed in the source tarball or installed.
             """))

        things.append(File("custom-executable", parent, True, full_text="""
             #!/bin/sh
             echo "Custom script executed"
             """))

    things.append(File("manage.py", executable=True, full_text="""
        #!/usr/bin/env python3
        from plainbox.provider_manager import setup, N_

        # You can inject other stuff here but please don't go overboard.
        #
        # In particular, if you need comprehensive compilation support to get
        # your bin/ populated then please try to discuss that with us in the
        # upstream project IRC channel #checkbox on irc.freenode.net.

        # NOTE: one thing that you could do here, that makes a lot of sense,
        # is to compute version somehow. This may vary depending on the
        # context of your provider. Future version of PlainBox will offer git,
        # bzr and mercurial integration using the versiontools library
        # (optional)

        setup(
            name={name!r},
            version="1.0",
            description=N_("The {name} provider"),
            gettext_domain="{gettext_domain}",
        )
        """))

    things.append(File(".gitignore", full_text="dist/*.tar.gz\nbuild/mo/*\n"))

    things.append(File(".bzrignore", full_text="dist/*.tar.gz\nbuild/mo/*\n"))


class StartProviderInvocation:

    def __init__(self, name):
        self.name = name

    def run(self):
        try:
            ProviderSkeleton(self.name).instantiate(
                '.', name=self.name,
                gettext_domain=re.sub("[.:]", "_", self.name))
        except SomethingInTheWay as exc:
            raise SystemExit(exc)


@docstring(
    # TRANSLATORS: please leave various options (both long and short forms),
    # environment variables and paths in their original form. Also keep the
    # special @EPILOG@ string. The first line of the translation is special and
    # is used as the help message. Please keep the pseudo-statement form and
    # don't finish the sentence with a dot. Pay extra attention to whitespace.
    # It must be correctly preserved or the result won't work. In particular
    # the leading whitespace *must* be preserved and *must* have the same
    # length on each line.
    N_("""
    create a new provider (directory)

    Creates a new provider from a built-in skeleton.

    @EPILOG@

    The name of the provider must follow the pattern ``YYYY.example.org:name``
    where ``YYYY`` is a four-digit year when the author of the provider owned
    the domain (here, ``example.org``) and ``name`` is arbitrary identifier
    that is managed by the owner of that domain. The identifier should be
    constrained to ASCII, digits and the dash character.

    This naming scheme allows anyone that ever owned a domain name to come up
    with non-clashing provider identifiers. Those identifiers are going to be
    used in fully qualified names of various objects.

    This command creates a new skeleton test provider for PlainBox. The
    generated content should be edited to fit a particular purpose.
    """))
class StartProviderCommand(PlainBoxCommand):

    def invoked(self, ns):
        return StartProviderInvocation(ns.name).run()

    def register_parser(self, subparsers):
        parser = self.add_subcommand(subparsers)
        parser.add_argument(
            'name',
            metavar=_("name"),
            type=IQN,
            # TRANSLATORS: please keep the YYYY.example... text unchanged or at
            # the very least translate only YYYY and some-name. In either case
            # some-name must be a reasonably-ASCII string (should be safe for a
            # portable directory name)
            help=_("provider name, eg: YYYY.example.org:some-name"))
        parser.set_defaults(command=self)