def test_pull_pdscs():
    with cmsis_server():
        json_path = tempfile.mkdtemp()
        data_path = tempfile.mkdtemp()
        c = cmsis_pack_manager.Cache(True,
                                     True,
                                     json_path=json_path,
                                     data_path=data_path,
                                     vidx_list=join(dirname(__file__),
                                                    'test-pack-index',
                                                    'vendors.list'))
        c.cache_everything()
        assert ("MyDevice" in c.index)
        assert ("MyFamily" == c.index["MyDevice"]["family"])
        assert ("MyBoard" in c.aliases)
        assert ("MyDevice" in c.aliases["MyBoard"]["mounted_devices"])
        assert (c.pack_from_cache(
            c.index["MyDevice"]).open("MyVendor.MyPack.pdsc"))
        c = cmsis_pack_manager.Cache(True,
                                     True,
                                     json_path=json_path,
                                     data_path=data_path,
                                     vidx_list=join(dirname(__file__),
                                                    'test-pack-index',
                                                    'vendors.list'))
        c.cache_everything()
        assert ("MyDevice" in c.index)
        assert ("MyFamily" == c.index["MyDevice"]["family"])
        assert ("MyBoard" in c.aliases)
        assert ("MyDevice" in c.aliases["MyBoard"]["mounted_devices"])
        assert (c.pack_from_cache(
            c.index["MyDevice"]).open("MyVendor.MyPack.pdsc"))
Exemple #2
0
def cache(tmpdir_factory, pack_ref):
    tmp_path = str(tmpdir_factory.mktemp("cpm"))
    c = cmsis_pack_manager.Cache(False,
                                 False,
                                 json_path=tmp_path,
                                 data_path=tmp_path)
    c.download_pack_list([pack_ref])
    return c
def test_print_cache_dir_cli(capsys):
    sys.argv = ["pack-manager", "print-cache-dir"]
    cmsis_pack_manager.pack_manager.main()
    captured = capsys.readouterr()

    c = cmsis_pack_manager.Cache(True, True)

    assert (c.data_path == captured.out.strip())
Exemple #4
0
    def _get_cache(self) -> "cmsis_pack_manager.Cache":
        """! @brief Handle 'clean' subcommand."""
        if not CPM_AVAILABLE:
            raise exceptions.CommandError(
                "'pack' subcommand is not available because cmsis-pack-manager is not installed"
            )

        verbosity = self._args.verbose - self._args.quiet
        return cmsis_pack_manager.Cache(verbosity < 0, False)
def test_add_pack_from_path():
    json_path = tempfile.mkdtemp()
    data_path = tempfile.mkdtemp()
    c = cmsis_pack_manager.Cache(
        True, True, json_path=json_path, data_path=data_path)
    c.add_pack_from_path(join(dirname(__file__), 'test-pack-index', 'MyVendor.MyPack.pdsc'))
    assert("MyDevice" in c.index)
    assert("MyBoard" in c.aliases)
    assert("MyDevice" in c.aliases["MyBoard"]["mounted_devices"])
Exemple #6
0
 def get_installed_targets():
     """! @brief Return a list of CmsisPackDevice objects for installed pack targets."""
     cache = cmsis_pack_manager.Cache(True, True)
     results = []
     for pack in ManagedPacks.get_installed_packs(cache=cache):
         pack_path = os.path.join(cache.data_path, pack.get_pack_name())
         pack = CmsisPack(pack_path)
         results += list(pack.devices)
     return sorted(results, key=lambda dev: dev.part_number)
Exemple #7
0
def test_empyt_cache():
    json_path = tempfile.mkdtemp()
    data_path = tempfile.mkdtemp()
    c = cmsis_pack_manager.Cache(
        True, True, json_path=json_path, data_path=data_path,
        vidx_list=join(dirname(__file__), 'test-pack-index', 'vendors.list'))
    try:
        c.index
    except Exception:
        assert False, "Unexpected exception raised on an empty cache"
def test_panic_handling():
    from cmsis_pack_manager import ffi
    c = cmsis_pack_manager.Cache(
        True, True, json_path=tempfile.mkdtemp(), data_path=tempfile.mkdtemp(),
        vidx_list=join(dirname(__file__), 'test-pack-index', 'vendors.list'))
    try:
        c._call_rust_parse(ffi.NULL)
        assert False
    except:
        pass
Exemple #9
0
def test_install_pack():
    with cmsis_server():
        json_path = tempfile.mkdtemp()
        data_path = tempfile.mkdtemp()
        c = cmsis_pack_manager.Cache(
            True, True, json_path=json_path, data_path=data_path,
            vidx_list=join(dirname(__file__), 'test-pack-index', 'vendors.list'))
        c.cache_descriptors()
        packs = c.packs_for_devices([c.index["MyDevice"]])
        c.download_pack_list(packs)
        assert(c.pack_from_cache(c.index["MyDevice"]).open("MyVendor.MyPack.pdsc"))
Exemple #10
0
 def get_installed_targets(
     cache: Optional[cmsis_pack_manager.Cache] = None
 ) -> List[CmsisPackDevice]:  # type:ignore
     """@brief Return a list of CmsisPackDevice objects for installed pack targets."""
     if cache is None:
         cache = cmsis_pack_manager.Cache(True, True)
     results = []
     for pack in ManagedPacks.get_installed_packs(cache=cache):
         pack_path = os.path.join(cache.data_path, pack.get_pack_name())
         pack = CmsisPack(pack_path)
         results += list(pack.devices)
     return sorted(results, key=lambda dev: dev.part_number)
def test_add_pack_from_path_cli():
    json_path = tempfile.mkdtemp()
    data_path = tempfile.mkdtemp()
    sys.argv = ["pack-manager", "add-packs",
                join(dirname(__file__), 'test-pack-index', 'MyVendor.MyPack.pdsc'),
                "--data-path", data_path,
                "--json-path", json_path,
                "--vidx-list", join(dirname(__file__), 'test-pack-index', 'vendors.list')]
    cmsis_pack_manager.pack_manager.main()
    c = cmsis_pack_manager.Cache(True, True, json_path=json_path, data_path=data_path)
    assert("MyDevice" in c.index)
    assert("MyBoard" in c.aliases)
    assert("MyDevice" in c.aliases["MyBoard"]["mounted_devices"])
def test_pull_pdscs_cli():
    with cmsis_server():
        json_path = tempfile.mkdtemp()
        data_path = tempfile.mkdtemp()
        sys.argv = ["pack-manager", "cache", "everything", "--data-path", data_path,
                    "--json-path", json_path,
                    "--vidx-list", join(dirname(__file__), 'test-pack-index', 'vendors.list')]
        cmsis_pack_manager.pack_manager.main()
        c = cmsis_pack_manager.Cache(True, True, json_path=json_path, data_path=data_path)
        assert("MyDevice" in c.index)
        assert("MyBoard" in c.aliases)
        assert("MyDevice" in c.aliases["MyBoard"]["mounted_devices"])
        assert(c.pack_from_cache(c.index["MyDevice"]).open("MyVendor.MyPack.pdsc"))
Exemple #13
0
    def get_installed_packs(cache=None):
        """! @brief Return a list containing CmsisPackRef objects for all installed packs."""
        cache = cache or cmsis_pack_manager.Cache(True, True)
        results = []
        # packs_for_devices() returns only unique packs.
        for pack in cache.packs_for_devices(cache.index.values()):
            # Generate full path to the .pack file.
            pack_path = os.path.join(cache.data_path, pack.get_pack_name())

            # If the .pack file exists, the pack is installed.
            if os.path.isfile(pack_path):
                results.append(pack)
        return results
Exemple #14
0
 def get_installed_targets():
     """! @brief Return a list of CmsisPackDevice objects for installed pack targets."""
     try:
         cache = cmsis_pack_manager.Cache(True, True)
         results = []
         for pack in ManagedPacks.get_installed_packs(cache=cache):
             pack_path = os.path.join(cache.data_path, pack.get_pack_name())
             pack = CmsisPack(pack_path)
             results += list(pack.devices)
         return sorted(results, key=lambda dev: dev.part_number)
     except FileNotFoundError:
         # cmsis-pack-manager can raise this exception if the cache is empty.
         pass
Exemple #15
0
 def inner_test(_zf):
     c = cmsis_pack_manager.Cache(True, True, data_path=data_path)
     device = {
         'from_pack': {
             'vendor': vendor,
             'pack': pack,
             'version': version
         }
     }
     c.pack_from_cache(device)
     assert (vendor in _zf.call_args[0][0])
     assert (pack in _zf.call_args[0][0])
     assert (version in _zf.call_args[0][0])
Exemple #16
0
 def inner_test(_open):
     _open.return_value.__enter__.return_value = MagicMock
     c = cmsis_pack_manager.Cache(True, True, data_path=data_path)
     device = {
         'from_pack': {
             'vendor': vendor,
             'pack': pack,
             'version': version
         }
     }
     c.pdsc_from_cache(device)
     assert (vendor in _open.call_args[0][0])
     assert (pack in _open.call_args[0][0])
     assert (version in _open.call_args[0][0])
Exemple #17
0
 def get_installed_packs(cache=None):
     """! @brief Return a list containing CmsisPackRef objects for all installed packs."""
     try:
         cache = cache or cmsis_pack_manager.Cache(True, True)
         results = []
         # packs_for_devices() returns only unique packs.
         for pack in cache.packs_for_devices(cache.index.values()):
             pack_path = os.path.join(cache.data_path, pack.get_pack_name())
             if os.path.isfile(pack_path):
                 results.append(pack)
         return results
     except FileNotFoundError:
         # cmsis-pack-manage can raise this exception if the cache is empty.
         return []
def test_dump_parts_cli():
    with cmsis_server():
        json_path = tempfile.mkdtemp()
        data_path = tempfile.mkdtemp()
        sys.argv = ["pack-manager", "cache", "packs", "--data-path", data_path,
                    "--json-path", json_path,
                    "--vidx-list", join(dirname(__file__), 'test-pack-index', 'vendors.list')]
        cmsis_pack_manager.pack_manager.main()
        dump_path = tempfile.mkdtemp()
        sys.argv = ["pack-manager", "dump-parts", dump_path, "Dev",
                    "--data-path", data_path,
                    "--json-path", json_path]
        cmsis_pack_manager.pack_manager.main()
        c = cmsis_pack_manager.Cache(True, True, json_path=json_path, data_path=data_path)
        assert exists(join(dump_path, "index.json"))
        for algo in c.index["MyDevice"]["algorithms"]:
            assert exists(join(dump_path, algo["file_name"]))
Exemple #19
0
    def do_pack(self):
        """! @brief Handle 'pack' subcommand."""
        if not CPM_AVAILABLE:
            LOG.error("'pack' command is not available because cmsis-pack-manager is not installed")
            return
        
        verbosity = self._args.verbose - self._args.quiet
        cache = cmsis_pack_manager.Cache(verbosity < 0, False)
        
        if self._args.clean:
            LOG.info("Removing all pack data...")
            cache.cache_clean()
        
        if self._args.update:
            LOG.info("Updating pack index...")
            cache.cache_descriptors()
        
        if self._args.show:
            packs = pack_target.ManagedPacks.get_installed_packs(cache)
            pt = self._get_pretty_table(["Vendor", "Pack", "Version"])
            for ref in packs:
                pt.add_row([
                            ref.vendor,
                            ref.pack,
                            ref.version,
                            ])
            print(pt)

        if self._args.find_devices or self._args.install_devices:
            if not cache.index:
                LOG.info("No pack index present, downloading now...")
                cache.cache_descriptors()
            
            patterns = self._args.find_devices or self._args.install_devices
            
            # Find matching part numbers.
            matches = set()
            for pattern in patterns:
                # Using fnmatch.fnmatch() was failing to match correctly.
                pat = re.compile(fnmatch.translate(pattern).rsplit('\\Z')[0], re.IGNORECASE)
                results = {name for name in cache.index.keys() if pat.search(name)}
                matches.update(results)
            
            if not matches:
                LOG.warning("No matching devices. Please make sure the pack index is up to date.")
                return
            
            if self._args.find_devices:
                # Get the list of installed pack targets.
                installed_targets = pack_target.ManagedPacks.get_installed_targets(cache=cache)
                installed_target_names = [target.part_number.lower() for target in installed_targets]
                
                pt = self._get_pretty_table(["Part", "Vendor", "Pack", "Version", "Installed"])
                for name in sorted(matches):
                    info = cache.index[name]
                    ref, = cache.packs_for_devices([info])
                    pt.add_row([
                                info['name'],
                                ref.vendor,
                                ref.pack,
                                ref.version,
                                info['name'].lower() in installed_target_names,
                                ])
                print(pt)
            elif self._args.install_devices:
                devices = [cache.index[dev] for dev in matches]
                packs = cache.packs_for_devices(devices)
                if not self._args.no_download:
                    print("Downloading packs (press Control-C to cancel):")
                else:
                    print("Would download packs:")
                for pack in packs:
                    print("    " + str(pack))
                if not self._args.no_download:
                    cache.download_pack_list(packs)
    def __init__(self):
        app = QApplication(sys.argv)
        self.window = QWidget()

        self.ui = Ui_Form()
        self.ui.setupUi(self.window)
        self.cache = cmsis_pack_manager.Cache(True, True)
        managedpack = ManagedPacks()
        self.packs = ManagedPacks().get_installed_packs()
        vendors = []
        current_packs = []
        self.current_targets = []

        for pack in self.packs:
            pack_path = os.path.join(self.cache.data_path,
                                     pack.get_pack_name())
            pack_temp = CmsisPack(pack_path)
            if len(pack_temp.devices) > 0:
                target_vendor = pack_temp.devices[0].vendor
            else:
                continue

            if target_vendor in vendors:
                pass
            else:
                vendors.append(target_vendor)

        for vendor in vendors:
            self.ui.vendor_list.addItem(vendor)

        for pack in self.packs:
            pack_path = os.path.join(self.cache.data_path,
                                     pack.get_pack_name())
            pack_temp = CmsisPack(pack_path)
            if len(pack_temp.devices) > 0:
                target_vendor = pack_temp.devices[0].vendor
            else:
                continue
            if target_vendor == self.ui.vendor_list.currentText():
                current_packs.append(pack)

        # print(ui.vendor_list.currentText())
        for current_pack in current_packs:
            # print(type(current_pack))
            pack_path = os.path.join(self.cache.data_path,
                                     current_pack.get_pack_name())
            # print(pack_path)
            pack = CmsisPack(pack_path)
            for device in pack.devices:
                self.current_targets.append(device)
        # print(current_targets)
        for target in self.current_targets:
            self.ui.device_list.addItem(target.part_number)

        probes = ConnectHelper.get_all_connected_probes(blocking=False)
        for probe in probes:
            self.ui.daplink_list.addItem(probe.description)
        if len(probes) > 0:
            self.probe = probes[0]
            print(self.probe)
        else:
            self.probe = None

        logger = logging.getLogger(__name__)
        logger.setLevel(level=logging.DEBUG)

        # StreamHandler
        stream_handler = logging.StreamHandler(self.ui.log.append)
        stream_handler.setLevel(level=logging.DEBUG)
        logger.addHandler(stream_handler)

        self.ui.vendor_list.currentTextChanged.connect(self.vendor_change)
        self.ui.device_list.currentIndexChanged.connect(self.device_change)

        self.ui.erase.clicked.connect(self.erase_device)
        self.ui.flash.clicked.connect(self.flash_device)
        self.ui.update_dap.clicked.connect(self.update_daplink)
        self.ui.connect.clicked.connect(self.open_session)
        self.ui.selsec_firmware.clicked.connect(self.select_file)
        self.ui.daplink_list.currentIndexChanged.connect(self.daplink_change)
        self.ui.flash_run.clicked.connect(self.flash_device_run)
        self.ui.halt.clicked.connect(self.device_halt)
        self.ui.run.clicked.connect(self.device_reset)
        self.ui.resume.clicked.connect(self.device_resume)
        self.ui.run.setDisabled(True)
        self.ui.halt.setDisabled(True)
        self.ui.erase.setDisabled(True)
        self.ui.flash.setDisabled(True)
        self.ui.flash_run.setDisabled(True)
        self.ui.resume.setDisabled(True)
        self.device_change()
        self.window.show()
        app.exec_()