Coverage for pass_import/formats/yaml.py: 100%
39 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-02-26 12:11 +0000
« prev ^ index » next coverage.py v7.4.3, created at 2024-02-26 12:11 +0000
1# -*- encoding: utf-8 -*-
2# pass import - Passwords importer swiss army knife
3# Copyright (C) 2017-2024 Alexandre PUJOL <alexandre@pujol.io>.
4#
6import yaml
8from pass_import.core import Cap, register_detecters
9from pass_import.detecter import Formatter
10from pass_import.errors import FormatError
11from pass_import.manager import PasswordImporter
14class YAML(Formatter, PasswordImporter):
15 """Base class for YAML based importers.
17 :param dict yml_format: Dictionary that need to be present in the imported
18 file to ensure the format is recognized.
19 :param str rootkey: Root key where to find the data to import in the YAML.
21 """
22 cap = Cap.FORMAT | Cap.IMPORT
23 format = 'yaml'
24 yml_format = {}
25 yamls = None
26 rootkey = ''
28 # Import method
30 def parse(self):
31 """Parse YAML based file."""
32 self.yamls = yaml.safe_load(self.file)
33 if not self.checkheader(self.header()):
34 raise FormatError()
36 keys = self.invkeys()
37 for block in self.yamls[self.rootkey]:
38 entry = {}
39 for key, value in block.items():
40 if value:
41 entry[keys.get(key, key)] = value
42 self.data.append(entry)
44 # Format recognition methods
46 def is_format(self):
47 """Return True if the file is a YAML file."""
48 try:
49 self.yamls = yaml.safe_load(self.file)
50 if isinstance(self.yamls, str):
51 return False
52 except (yaml.scanner.ScannerError, yaml.parser.ParserError,
53 UnicodeDecodeError):
54 return False
55 return True
57 def checkheader(self, header, only=False):
58 """Ensure the file header is the same than the pm header."""
59 for key, value in header.items():
60 if self.yamls.get(key, '') != value:
61 return False
62 return True
64 @classmethod
65 def header(cls):
66 """Header for YML file."""
67 return cls.yml_format
70register_detecters(YAML)