743c874dfcb00e712cb1e6fbfadfefcb024f92fd
[sdc/sdc-distribution-client.git] /
1 ######################## BEGIN LICENSE BLOCK ########################
2 # This library is free software; you can redistribute it and/or
3 # modify it under the terms of the GNU Lesser General Public
4 # License as published by the Free Software Foundation; either
5 # version 2.1 of the License, or (at your option) any later version.
6 #
7 # This library is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 # Lesser General Public License for more details.
11 #
12 # You should have received a copy of the GNU Lesser General Public
13 # License along with this library; if not, write to the Free Software
14 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
15 # 02110-1301  USA
16 ######################### END LICENSE BLOCK #########################
17
18 __version__ = "1.0.3"
19 from sys import version_info
20
21
22 def detect(aBuf):
23     if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or
24             (version_info >= (3, 0) and not isinstance(aBuf, bytes))):
25         raise ValueError('Expected a bytes object, not a unicode object')
26
27     from . import universaldetector
28     u = universaldetector.UniversalDetector()
29     u.reset()
30     u.feed(aBuf)
31     u.close()
32     return u.result
33
34 def _description_of(path):
35     """Return a string describing the probable encoding of a file."""
36     from charade.universaldetector import UniversalDetector
37
38     u = UniversalDetector()
39     for line in open(path, 'rb'):
40         u.feed(line)
41     u.close()
42     result = u.result
43     if result['encoding']:
44         return '%s: %s with confidence %s' % (path,
45                                               result['encoding'],
46                                               result['confidence'])
47     else:
48         return '%s: no result' % path
49
50
51 def charade_cli():
52     """
53     Script which takes one or more file paths and reports on their detected
54     encodings
55
56     Example::
57
58         % chardetect.py somefile someotherfile
59         somefile: windows-1252 with confidence 0.5
60         someotherfile: ascii with confidence 1.0
61
62     """
63     from sys import argv
64     for path in argv[1:]:
65         print(_description_of(path))
66