Exemple #1
0
    def _sanity_check(self):
        """Check to see if the current directory matches what is created by PblProjectCreator.run.

        Raises an InvalidProjectException or an OutdatedProjectException if everything isn't quite right.
        """

        if self.project_type not in ('native', 'package'):
            if self.project_type == 'pebblejs':
                raise InvalidProjectException(
                    "Pebble.js is not part of the pebble SDK, and so the SDK can't build it.\n"
                    "Either use CloudPebble or follow the instructions at "
                    "https://github.com/pebble/pebblejs/blob/master/README.md#getting-started"
                )
            else:
                raise InvalidProjectException(
                    "Unsupported project type '%s'." % self.project_type)

        if os.path.islink(os.path.join(self.project_dir, 'pebble_app.ld')) \
                or os.path.exists(os.path.join(self.project_dir, 'resources/src/resource_map.json')) \
                or not os.path.exists(os.path.join(self.project_dir, 'wscript')):
            raise OutdatedProjectException(
                "This project is very outdated, and cannot be handled by this SDK."
            )

        if self.sdk_version != SDK_VERSION:
            if sdk_version() != '2.9':
                raise OutdatedProjectException(
                    "This projected is outdated (try 'pebble convert-project' or"
                    "'pebble sdk install 2.9')")
Exemple #2
0
    def _sanity_check(self):
        """Check to see if the current directory matches what is created by PblProjectCreator.run.

        Raises an InvalidProjectException or an OutdatedProjectException if everything isn't quite right.
        """

        if self.project_type not in  ('native', 'package', 'rocky'):
            if self.project_type == 'pebblejs':
                raise InvalidProjectException("Pebble.js is not part of the pebble SDK, and so the SDK can't build it.\n"
                                              "Either use CloudPebble or follow the instructions at "
                                              "https://github.com/pebble/pebblejs/blob/master/README.md#getting-started")
            else:
                raise InvalidProjectException("Unsupported project type '%s'." % self.project_type)

        if os.path.islink(os.path.join(self.project_dir, 'pebble_app.ld')) \
                or os.path.exists(os.path.join(self.project_dir, 'resources/src/resource_map.json')) \
                or not os.path.exists(os.path.join(self.project_dir, 'wscript')):
            raise OutdatedProjectException("This project is very outdated, and cannot be handled by this SDK.")

        if self.sdk_version == '2.9':
            if sdk_version() != '2.9':
                raise OutdatedProjectException("This projected is outdated (try 'pebble convert-project' or"
                                               "'pebble sdk install 2.9')")
        elif self.sdk_version != SDK_VERSION:
            raise PebbleProjectException("An invalid value of '{}' was found in the 'sdkVersion' field of the "
                                         "project's package.json. The latest supported value for this field is '{}'.".
                                         format(self.sdk_version, SDK_VERSION))
Exemple #3
0
    def submit_event(self, event, force=False, **data):
        analytics = {
            'event': event,
            'identity': self._get_identity(),
            'platform': 'native_sdk',
            'sdk': {
                'host': self._get_host_info(),
                'version': sdk_version(),
                'tool_version': __version__,
            },
            'data': data.copy()
        }
        try:
            analytics['sdk']['project'] = self._get_project_info()
        except PebbleProjectException:
            pass


        td_obj = self._flatten(analytics)

        fields = {
            'json': json.dumps(td_obj)
        }
        if force:
            requests.post(self.TD_SERVER, data=fields)
            logger.debug("Synchronously transmitting analytics data: {}".format(analytics))
        else:
            logger.debug("Queueing analytics data: {}".format(analytics))
            self._enqueue(fields)
Exemple #4
0
    def check_project_directory(project_dir):
        """Check to see if the current directory matches what is created by PblProjectCreator.run.

        Raises an InvalidProjectException or an OutdatedProjectException if everything isn't quite right.
        """

        if not os.path.isdir(os.path.join(project_dir, 'src')):
            raise InvalidProjectException("This is not a project directory.")

        try:
            with open(os.path.join(project_dir, "appinfo.json"), "r") as f:
                try:
                    app_info = json.load(f)
                except ValueError as ex:
                    raise InvalidJSONException("Could not parse appinfo.json because of the following error: %s" % ex)
        except IOError:
            raise InvalidProjectException("Couldn't open project info.")

        if os.path.islink(os.path.join(project_dir, 'pebble_app.ld')) \
                or os.path.exists(os.path.join(project_dir, 'resources/src/resource_map.json')) \
                or not os.path.exists(os.path.join(project_dir, 'wscript')):
            raise OutdatedProjectException("This project is very outdated, and cannot be handled by this SDK.")
        if app_info.get("sdkVersion", None) != SDK_VERSION:
            if sdk_version() != '2.9':
                raise OutdatedProjectException("This projected is outdated (try 'pebble convert-project' or"
                                               "'pebble sdk install 2.9')")
Exemple #5
0
    def submit_event(self, event, force=False, **data):
        analytics = {
            'event': event,
            'identity': self._get_identity(),
            'platform': 'native_sdk',
            'sdk': {
                'host': self._get_host_info(),
                'version': sdk_version(),
                'tool_version': __version__,
            },
            'data': data.copy()
        }
        try:
            analytics['sdk']['project'] = self._get_project_info()
        except PebbleProjectException:
            pass

        td_obj = self._flatten(analytics)

        fields = {'json': json.dumps(td_obj)}
        if force:
            requests.post(self.TD_SERVER, data=fields)
            logger.debug(
                "Synchronously transmitting analytics data: {}".format(
                    analytics))
        else:
            logger.debug("Queueing analytics data: {}".format(analytics))
            self._enqueue(fields)
Exemple #6
0
    def __call__(self, args):
        super(NewProjectCommand, self).__call__(args)

        project_path = args.name
        project_name = os.path.split(project_path)[1]
        sdk2 = self.sdk == "2.9" or (self.sdk is None
                                     and sdk_version() == "2.9")

        template_paths = [
            os.path.join(self.get_sdk_path(), 'pebble', 'common', 'templates',
                         'app'),
            os.path.join(self.get_sdk_path(), 'pebble', 'common', 'templates'),
            os.path.join(os.path.dirname(__file__), '..', '..', 'sdk',
                         'templates'),
        ]
        file_list = [('gitignore', '.gitignore'),
                     ('simple.c' if args.simple else 'main.c',
                      'src/{}.c'.format(project_name)),
                     ('wscript_sdk2' if sdk2 else 'wscript', 'wscript')]
        if args.javascript:
            file_list.extend([('app.js', 'src/js/app.js'),
                              ('pebble-js-app.js', 'src/js/pebble-js-app.js')])
        if args.worker:
            file_list.append(
                ('worker.c', 'worker/{}_worker.c'.format(project_name)))

        _copy_template(args.name, template_paths,
                       ['package.json', 'appinfo.json'], file_list,
                       ['resources'])

        post_event("sdk_create_project",
                   javascript=args.javascript,
                   worker=args.worker)
        print("Created new project {}".format(args.name))
Exemple #7
0
    def __call__(self, args):
        super(NewProjectCommand, self).__call__(args)

        project_path = args.name
        project_name = os.path.split(project_path)[1]
        sdk2 = self.sdk == "2.9" or (self.sdk is None and sdk_version() == "2.9")

        template_paths = [
            os.path.join(self.get_sdk_path(), 'pebble', 'common', 'templates', 'app'),
            os.path.join(self.get_sdk_path(), 'pebble', 'common', 'templates'),
            os.path.join(os.path.dirname(__file__), '..', '..', 'sdk', 'templates'),
        ]
        file_list = [
            ('gitignore', '.gitignore'),
            ('simple.c' if args.simple else 'main.c', 'src/{}.c'.format(project_name)),
            ('wscript_sdk2' if sdk2 else 'wscript', 'wscript')
        ]
        if args.javascript:
            file_list.extend([('app.js', 'src/js/app.js'), ('pebble-js-app.js', 'src/js/pebble-js-app.js')])
        if args.worker:
            file_list.append(('worker.c', 'worker/{}_worker.c'.format(project_name)))

        _copy_template(args.name, template_paths, ['package.json', 'appinfo.json'], file_list, ['resources'])

        post_event("sdk_create_project", javascript=args.javascript, worker=args.worker)
        print("Created new project {}".format(args.name))
Exemple #8
0
    def check_project_directory(project_dir):
        """Check to see if the current directory matches what is created by PblProjectCreator.run.

        Raises an InvalidProjectException or an OutdatedProjectException if everything isn't quite right.
        """

        if not os.path.isdir(os.path.join(project_dir, 'src')):
            raise InvalidProjectException("This is not a project directory.")

        try:
            with open(os.path.join(project_dir, "appinfo.json"), "r") as f:
                try:
                    app_info = json.load(f)
                except ValueError as ex:
                    raise InvalidJSONException(
                        "Could not parse appinfo.json because of the following error: %s"
                        % ex)
        except IOError:
            raise InvalidProjectException("Couldn't open project info.")

        if os.path.islink(os.path.join(project_dir, 'pebble_app.ld')) \
                or os.path.exists(os.path.join(project_dir, 'resources/src/resource_map.json')) \
                or not os.path.exists(os.path.join(project_dir, 'wscript')):
            raise OutdatedProjectException(
                "This project is very outdated, and cannot be handled by this SDK."
            )
        if app_info.get("sdkVersion", None) != SDK_VERSION:
            if sdk_version() != '2.9':
                raise OutdatedProjectException(
                    "This projected is outdated (try 'pebble convert-project' or"
                    "'pebble sdk install 2.9')")
Exemple #9
0
 def _shared_parser(cls):
     parser = argparse.ArgumentParser(add_help=False)
     if len(cls.valid_connections) < 2 :
         group = parser
     else :
         group = parser.add_mutually_exclusive_group()
     if 'phone' in cls.valid_connections:
         group.add_argument('--phone', metavar='phone_ip',
                             help="When using the developer connection, your phone's IP or hostname. "
                                  "Equivalent to PEBBLE_PHONE.")
     if 'qemu' in cls.valid_connections:
         group.add_argument('--qemu', nargs='?', const='localhost:12344', metavar='host',
                             help="Use this option to connect directly to a QEMU instance. "
                                  "Equivalent to PEBBLE_QEMU.")
     if 'cloudpebble' in cls.valid_connections:
         group.add_argument('--cloudpebble', action='store_true', help="Use this option to connect to your phone via"
                                                                       " the CloudPebble connection. Equivalent to "
                                                                       "PEBBLE_CLOUDPEBBLE.")
     if 'emulator' in cls.valid_connections:
         emu_group = group.add_argument_group()
         emu_group.add_argument('--emulator', type=str, help="Launch an emulator. Equivalent to PEBBLE_EMULATOR.",
                            choices=pebble_platforms)
         emu_group.add_argument('--sdk', type=str, help="SDK version to launch. Defaults to the active SDK"
                                                    " (currently {})".format(sdk_version()))
     if 'serial' in cls.valid_connections:
         group.add_argument('--serial', type=str, help="Connected directly, given a path to a serial device.")
     return super(PebbleCommand, cls)._shared_parser() + [parser]
Exemple #10
0
 def add_argument_handler(cls, parser):
     emu_group = parser.add_argument_group()
     emu_group.add_argument(
         '--emulator',
         type=str,
         help="Launch an emulator. Equivalent to PEBBLE_EMULATOR.",
         choices=pebble_platforms)
     emu_group.add_argument(
         '--sdk',
         type=str,
         help="SDK version to launch. Defaults to the active SDK"
         " (currently {})".format(sdk_version()))
Exemple #11
0
    def __call__(self, args):
        super(NewProjectCommand, self).__call__(args)

        template_paths = [
            os.path.join(self.get_sdk_path(), 'pebble', 'common', 'templates'),
            os.path.join(os.path.dirname(__file__), '..', '..', 'sdk',
                         'templates')
        ]

        sdk = self.sdk or sdk_version()
        sdk2 = (sdk == "2.9")

        if args.rocky:
            if sdk2:
                raise ToolError("--rocky is not compatible with SDK 2.9")
            if args.simple or args.worker:
                raise ToolError(
                    "--rocky is incompatible with --simple and --worker")
            options = ['rocky']
        else:
            options = ['app']
            if args.javascript:
                options.append('javascript')
            if args.simple:
                options.append('simple')
            if args.worker:
                options.append('worker')

        # Hack for old SDKs that need an appinfo, because the declarative system can't
        # handle "this, but only if not that." For "tintin" SDKs and unparseble
        # versions, assume this hack is not needed.
        version_number = version_to_key(sdk)
        if version_number[:5] != (0, 0, 0, 0, 0) and \
           version_number < (3, 13, 0):
            options.append('appinfo')

        with open(
                extant_path(
                    os.path.join(x, "templates.json")
                    for x in template_paths)) as f:
            template_layout = json.load(f)

        _copy_from_template(template_layout, extant_path(template_paths),
                            args.name, options)

        post_event("sdk_create_project",
                   javascript=args.javascript or args.rocky,
                   worker=args.worker,
                   rocky=args.rocky)
        print("Created new project {}".format(args.name))
Exemple #12
0
    def _connect_args(cls, args):
        emulator_platform = getattr(args, 'emulator', None)
        emulator_sdk = getattr(args, 'sdk', None)
        if emulator_platform:
            return emulator_platform, emulator_sdk
        elif 'PEBBLE_EMULATOR' in os.environ:
            emulator_platform = os.environ['PEBBLE_EMULATOR']
            if emulator_platform not in pebble_platforms:
                raise ToolError("PEBBLE_EMULATOR is set to '{}', which is not a valid platform "
                                "(pick from {})".format(emulator_platform, ', '.join(pebble_platforms)))
            emulator_sdk = os.environ.get('PEBBLE_EMULATOR_VERSION', sdk_version())
        else:
            running = cls.get_running_emulators()
            if len(running) == 1:
                emulator_platform, emulator_sdk = running[0]
            elif len(running) > 1:
                raise ToolError("Multiple emulators are running; you must specify which to use.")

        return (emulator_platform, emulator_sdk)
Exemple #13
0
 def _connect(self, args):
     self._set_debugging(args.v)
     if getattr(args, 'phone', None):
         return self._connect_phone(args.phone)
     elif getattr(args, 'qemu', None):
         return self._connect_qemu(args.qemu)
     elif getattr(args, 'emulator', None):
         return self._connect_emulator(args.emulator, args.sdk)
     elif getattr(args, 'cloudpebble', None):
         return self._connect_cloudpebble()
     elif getattr(args, 'serial', None):
         return self._connect_serial(args.serial)
     else:
         if 'phone' in self.valid_connections and 'PEBBLE_PHONE' in os.environ:
             return self._connect_phone(os.environ['PEBBLE_PHONE'])
         elif 'qemu' in self.valid_connections and 'PEBBLE_QEMU' in os.environ:
             return self._connect_qemu(os.environ['PEBBLE_QEMU'])
         elif 'cloudpebble' in self.valid_connections and os.environ.get('PEBBLE_CLOUDPEBBLE', False):
             return self._connect_cloudpebble()
         elif 'serial' in self.valid_connections and 'PEBBLE_BT_SERIAL' in os.environ:
             return self._connect_serial(os.environ['PEBBLE_BT_SERIAL'])
         elif 'emulator' in self.valid_connections:
             running = []
             emulator_platform = None
             emulator_sdk = None
             if 'PEBBLE_EMULATOR' in os.environ:
                 emulator_platform = os.environ['PEBBLE_EMULATOR']
                 if emulator_platform not in pebble_platforms:
                     raise ToolError("PEBBLE_EMULATOR is set to '{}', which is not a valid platform "
                                     "(pick from {})".format(emulator_platform, ', '.join(pebble_platforms)))
                 emulator_sdk = os.environ.get('PEBBLE_EMULATOR_VERSION', sdk_version())
             else:
                 for platform, sdks in get_all_emulator_info().items():
                     for sdk in sdks:
                         if ManagedEmulatorTransport.is_emulator_alive(platform, sdk):
                             running.append((platform, sdk))
                 if len(running) == 1:
                     emulator_platform, emulator_sdk = running[0]
                 elif len(running) > 1:
                     raise ToolError("Multiple emulators are running; you must specify which to use.")
             if emulator_platform is not None:
                 return self._connect_emulator(emulator_platform, emulator_sdk)
     raise ToolError("No pebble connection specified.")
Exemple #14
0
    def __call__(self, args):
        super(NewProjectCommand, self).__call__(args)

        template_paths = [
            os.path.join(self.get_sdk_path(), 'pebble', 'common', 'templates'),
            os.path.join(os.path.dirname(__file__), '..', '..', 'sdk', 'templates')
        ]

        sdk = self.sdk or sdk_version()
        sdk2 = (sdk == "2.9")

        if args.rocky:
            if sdk2:
                raise ToolError("--rocky is not compatible with SDK 2.9")
            if args.simple or args.worker:
                raise ToolError("--rocky is incompatible with --simple and --worker")
            options = ['rocky']
        else:
            options = ['app']
            if args.javascript:
                options.append('javascript')
            if args.simple:
                options.append('simple')
            if args.worker:
                options.append('worker')

        # Hack for old SDKs that need an appinfo, because the declarative system can't
        # handle "this, but only if not that." For "tintin" SDKs and unparseble
        # versions, assume this hack is not needed.
        version_number = version_to_key(sdk)
        if version_number[:5] != (0, 0, 0, 0, 0) and \
           version_number < (3, 13, 0):
            options.append('appinfo')

        with open(extant_path(os.path.join(x, "templates.json") for x in template_paths)) as f:
            template_layout = json.load(f)

        _copy_from_template(template_layout, extant_path(template_paths), args.name, options)

        post_event("sdk_create_project", javascript=args.javascript or args.rocky, worker=args.worker, rocky=args.rocky)
        print("Created new project {}".format(args.name))
Exemple #15
0
    def _connect_args(cls, args):
        emulator_platform = getattr(args, 'emulator', None)
        emulator_sdk = getattr(args, 'sdk', None)
        if emulator_platform:
            return emulator_platform, emulator_sdk
        elif 'PEBBLE_EMULATOR' in os.environ:
            emulator_platform = os.environ['PEBBLE_EMULATOR']
            if emulator_platform not in pebble_platforms:
                raise ToolError(
                    "PEBBLE_EMULATOR is set to '{}', which is not a valid platform "
                    "(pick from {})".format(emulator_platform,
                                            ', '.join(pebble_platforms)))
            emulator_sdk = os.environ.get('PEBBLE_EMULATOR_VERSION',
                                          sdk_version())
        else:
            running = cls.get_running_emulators()
            if len(running) == 1:
                emulator_platform, emulator_sdk = running[0]
            elif len(running) > 1:
                raise ToolError(
                    "Multiple emulators are running; you must specify which to use."
                )

        return (emulator_platform, emulator_sdk)
Exemple #16
0
    def __call__(self, args):
        super(NewProjectCommand, self).__call__(args)

        # User can give a path to a new project dir
        project_path = args.name
        project_name = os.path.split(project_path)[1]
        project_root = os.path.join(os.getcwd(), project_path)

        project_src = os.path.join(project_root, "src")

        # Create directories
        try:
            os.makedirs(project_root)
            os.makedirs(os.path.join(project_root, "resources"))
            os.makedirs(project_src)
        except OSError as e:
            if e.errno == errno.EEXIST:
                raise ToolError(
                    "A directory called '{}' already exists.".format(
                        args.name))
            raise

        project_template_path = os.path.join(self.get_sdk_path(), 'pebble',
                                             'common', 'templates')
        if not os.path.exists(project_template_path):
            project_template_path = os.path.join(os.path.dirname(__file__),
                                                 '..', '..', 'sdk',
                                                 'templates')

        # Create main .c file
        if args.simple:
            default_main = os.path.join(project_template_path, 'simple.c')
        else:
            default_main = os.path.join(project_template_path, 'main.c')
        copy2(default_main,
              os.path.join(project_src, "{}.c".format(project_name)))

        # Add appinfo.json file
        with open(os.path.join(project_template_path, 'appinfo.json')) as f:
            appinfo = Template(f.read())

        with open(os.path.join(project_root, "appinfo.json"), "w") as f:
            f.write(
                appinfo.substitute(uuid=str(uuid4()),
                                   project_name=project_name,
                                   sdk_version=SDK_VERSION))

        # Add .gitignore file
        copy2(os.path.join(project_template_path, 'gitignore'),
              os.path.join(project_root, '.gitignore'))

        # Add javascript files if applicable
        if args.javascript:
            project_js_src = os.path.join(project_src, "js")
            os.makedirs(project_js_src)

            try:
                copy2(os.path.join(project_template_path, 'app.js'),
                      os.path.join(project_js_src, 'app.js'))
            except IOError as e:
                if e.errno != errno.ENOENT:
                    raise e
                copy2(os.path.join(project_template_path, 'pebble-js-app.js'),
                      os.path.join(project_js_src, 'pebble-js-app.js'))

        # Add background worker files if applicable
        if args.worker:
            project_worker_src = os.path.join(project_root, "worker_src")
            os.makedirs(project_worker_src)
            # Add simple source file
            copy2(
                os.path.join(project_template_path, 'worker.c'),
                os.path.join(project_worker_src,
                             "{}_worker.c".format(project_name)))

        # Add wscript file
        if self.sdk == "2.9" or (self.sdk is None and sdk_version() == "2.9"):
            copy2(os.path.join(project_template_path, 'wscript_sdk2'),
                  os.path.join(project_root, "wscript"))
        else:
            copy2(os.path.join(project_template_path, 'wscript'),
                  os.path.join(project_root, "wscript"))

        post_event("sdk_create_project",
                   javascript=args.javascript,
                   worker=args.worker)
        print("Created new project {}".format(args.name))
Exemple #17
0
    def __call__(self, args):
        super(NewProjectCommand, self).__call__(args)

        # User can give a path to a new project dir
        project_path = args.name
        project_name = os.path.split(project_path)[1]
        project_root = os.path.join(os.getcwd(), project_path)

        project_src = os.path.join(project_root, "src")

        # Create directories
        try:
            os.makedirs(project_root)
            os.makedirs(os.path.join(project_root, "resources"))
            os.makedirs(project_src)
        except OSError as e:
            if e.errno == errno.EEXIST:
                raise ToolError("A directory called '{}' already exists.".format(args.name))
            raise

        project_template_path = os.path.join(self.get_sdk_path(), 'pebble', 'common', 'templates')
        if not os.path.exists(project_template_path):
            project_template_path = os.path.join(os.path.dirname(__file__), '..', '..', 'sdk', 'templates')

        # Create main .c file
        if args.simple:
            default_main = os.path.join(project_template_path, 'simple.c')
        else:
            default_main = os.path.join(project_template_path, 'main.c')
        copy2(default_main, os.path.join(project_src, "{}.c".format(project_name)))

        # Add appinfo.json file
        with open(os.path.join(project_template_path, 'appinfo.json')) as f:
            appinfo = Template(f.read())

        with open(os.path.join(project_root, "appinfo.json"), "w") as f:
            f.write(appinfo.substitute(uuid=str(uuid4()), project_name=project_name, sdk_version=SDK_VERSION))

        # Add .gitignore file
        copy2(os.path.join(project_template_path, 'gitignore'), os.path.join(project_root, '.gitignore'))

        # Add javascript files if applicable
        if args.javascript:
            project_js_src = os.path.join(project_src, "js")
            os.makedirs(project_js_src)

            try:
                copy2(os.path.join(project_template_path, 'app.js'),
                      os.path.join(project_js_src, 'app.js'))
            except IOError as e:
                if e.errno != errno.ENOENT:
                    raise e
                copy2(os.path.join(project_template_path, 'pebble-js-app.js'),
                      os.path.join(project_js_src, 'pebble-js-app.js'))

        # Add background worker files if applicable
        if args.worker:
            project_worker_src = os.path.join(project_root, "worker_src")
            os.makedirs(project_worker_src)
            # Add simple source file
            copy2(os.path.join(project_template_path, 'worker.c'),
                  os.path.join(project_worker_src, "{}_worker.c".format(project_name)))

        # Add wscript file
        if self.sdk == "2.9" or (self.sdk is None and sdk_version() == "2.9"):
            copy2(os.path.join(project_template_path, 'wscript_sdk2'), os.path.join(project_root, "wscript"))
        else:
            copy2(os.path.join(project_template_path, 'wscript'), os.path.join(project_root, "wscript"))

        post_event("sdk_create_project", javascript=args.javascript, worker=args.worker)
        print("Created new project {}".format(args.name))
Exemple #18
0
 def add_argument_handler(cls, parser):
     emu_group = parser.add_argument_group()
     emu_group.add_argument('--emulator', type=str, help="Launch an emulator. Equivalent to PEBBLE_EMULATOR.",
                        choices=pebble_platforms)
     emu_group.add_argument('--sdk', type=str, help="SDK version to launch. Defaults to the active SDK"
                                                " (currently {})".format(sdk_version()))