Skip to content

Commit

Permalink
Add support for Pint's contexts #18
Browse files Browse the repository at this point in the history
  • Loading branch information
deanishe committed Nov 2, 2017
1 parent 534ccca commit 384fc3a
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 11 deletions.
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@
Changelog
=========

### [3.2][v3.2] ###

Released 2017-11-02.

- Add support for Pint's contexts #18


### [3.1][v3.1] ###

Released 2017-11-02.

- Replace Yahoo! Finance with [openexchangerates.org][openx] #27


### [3.0][v3.0] ###

Released 2017-07-16.
Expand All @@ -14,6 +28,7 @@ Released 2017-07-16.
- Update Alfred-Workflow
- Update Pint


### [2.6][v2.6] ###

Released 2017-06-15.
Expand Down Expand Up @@ -103,3 +118,6 @@ Released 2014-08-09.
[v2.5]: https://github.com/deanishe/alfred-convert/releases/tag/v2.5
[v2.6]: https://github.com/deanishe/alfred-convert/releases/tag/v2.6
[v3.0]: https://github.com/deanishe/alfred-convert/releases/tag/v3.0
[v3.1]: https://github.com/deanishe/alfred-convert/releases/tag/v3.1
[v3.2]: https://github.com/deanishe/alfred-convert/releases/tag/v3.2
[openx]: https://openexchangerates.org/
Binary file not shown.
13 changes: 10 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,23 +54,27 @@ Usage
<a name="conversions"></a>
### Conversions ###

**NOTE**: To perform conversions between fiat currencies, you must set a key for the [openexchangerates.org][openx] API in the workflow's [configuration sheet](#configuration). You can sign up for a free account [here][openx-free].
**NOTE**: To perform conversions between fiat currencies, you must set a key for the [openexchangerates.org][openx] API in the workflow's [configuration sheet](#configuration). You can sign up for a free account [here][openx-free]. When you're signed up, copy the **App ID** from the email you receive or [this page][openx-appid] into the `APP_KEY` field in the [configuration sheet](#configuration).

- `conv <quantity> <from unit> [<to unit>]` — Perform a conversion
- `conv [<context>] <quantity> <from unit> [<to unit>]` — Perform a conversion
- `` or `⌘C` — Copy the result to the pasteboard
- `⌘↩` — Add/remove destination unit as default for this dimensionality
- `⌘L` — Show result in Alfred's Large Type window

If no destination unit is specified, any defaults you've saved will be used (that aren't the same as the source unit).

The syntax is simple: the quantity, the unit you want to convert from then (optionally) the unit you want to convert to. For example:
The syntax is simple: an optional context, the quantity, the unit you want to convert from then (optionally) the unit you want to convert to. For example:

- `conv 128 mph kph`
- `conv 72in cm`
- `conv 100psi bar`
- `conv 20.5 m/s mph`
- `conv 100 eur gbp`

Or with a context:

- `conv spectroscopy 1Å eV` (or `conv sp 1Å eV`)

It doesn't matter if there is a space between the quantity and the units or not. Alfred-Convert will tell you if it doesn't understand your query or know the units.

Actioning an item (selecting it and hitting ``) will copy it to the clipboard. Using `⌘+L` will display the result in Alfred's large text window, `⌘+C` will copy the selected result to the clipboard.
Expand Down Expand Up @@ -151,6 +155,7 @@ See [CHANGELOG][changelog] for more information.

| Release | Date |
|-------------|----------------|
| [3.1][v3.2] | 2017-11-02 |
| [3.1][v3.1] | 2017-11-02 |
| [3.0][v3.0] | 2017-07-16 |
| [2.6][v2.6] | 2017-06-15 |
Expand Down Expand Up @@ -200,6 +205,8 @@ All other code/media are released under the [MIT Licence][mit].
[v2.6]: https://github.com/deanishe/alfred-convert/releases/tag/v2.6
[v3.0]: https://github.com/deanishe/alfred-convert/releases/tag/v3.0
[v3.1]: https://github.com/deanishe/alfred-convert/releases/tag/v3.1
[v3.2]: https://github.com/deanishe/alfred-convert/releases/tag/v3.2
[cryptocompare]: https://www.cryptocompare.com/
[openx]: https://openexchangerates.org/
[openx-free]: https://openexchangerates.org/signup/free
[openx-appid]: https://openexchangerates.org/account/app-ids
38 changes: 31 additions & 7 deletions src/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ def __init__(self, number, dimensionality, from_unit, to_unit=None):
def __repr__(self):
return ('Input(number={!r}, dimensionality={!r}, '
'from_unit={!r}, to_unit={!r})').format(
self.number,
self.dimensionality, self.from_unit, self.to_unit)
self.number, self.dimensionality, self.from_unit,
self.to_unit)

def __str__(self):
return self.__repr__()
Expand Down Expand Up @@ -160,22 +160,40 @@ def convert(self, i):
for u in units:
to_unit = ureg.Quantity(1, u)
conv = qty.to(to_unit)
log.debug('%s -> %s = %s', i.from_unit, u, conv)
log.debug('[convert] %s -> %s = %s', i.from_unit, u, conv)
results.append(Conversion(i.number, i.from_unit,
conv.magnitude, u, i.dimensionality))

return results

def parse(self, query):
"""Parse user query into `Input`."""
# Parse number from start of query
ctx = []
qty = []

# Parse optional context
for c in query:
if c in 'abcdefghijklmnopqrstuvwxyz':
ctx.append(c)
else:
break

if ctx:
ctx = ''.join(ctx)
ureg.enable_contexts(ctx)
log.debug('[parser] context=%s', ctx)
query = query[len(ctx):].strip()

# Parse from quantity
for c in query:
if c in '1234567890.,':
qty.append(c)
else:
break
if not len(qty):
if ctx:
raise ValueError('No quantity')

raise ValueError('Start your query with a number')

tail = query[len(qty):].strip()
Expand All @@ -184,14 +202,16 @@ def parse(self, query):
if not len(tail):
raise ValueError('No units specified')

log.debug('quantity : %s tail : %s', qty, tail)
log.debug('[parser] quantity=%s, tail=%s', qty, tail)

# Try to parse rest of query into a pair of units
from_unit = to_unit = None
units = [s.strip() for s in tail.split()]
from_unit = units[0]
log.debug('[parser] from_unit=%s', from_unit)
if len(units) > 1:
to_unit = units[1]
log.debug('[parser] to_unit=%s', to_unit)
if len(units) > 2:
raise ValueError('More than 2 units specified')

Expand All @@ -212,7 +232,7 @@ def parse(self, query):
i = Input(from_unit.magnitude, unicode(from_unit.dimensionality),
unicode(from_unit.units), tu)

log.debug(i)
log.debug('[parser] %s', i)

return i

Expand Down Expand Up @@ -298,7 +318,7 @@ def convert(query):
else:
try:
results = c.convert(i)
log.debug('results=%r', results)
# log.debug('results=%r', results)
except NoToUnits:
log.critical(u'No to_units (or defaults) for %s', i.dimensionality)
error = u'No destination units (or defaults) for {}'.format(
Expand All @@ -309,6 +329,10 @@ def convert(query):
error = u"Can't convert from {} {} to {} {}".format(
err.units1, err.dim1, err.units2, err.dim2)

except KeyError as err:
log.critical(u'invalid context (%s): %s', i.context, err)
error = u'Unknown context: {}'.format(i.context)

if not error and not results:
error = 'Conversion input not understood'

Expand Down
2 changes: 1 addition & 1 deletion src/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,7 @@ UPDATE_INTERVAL is the number of minutes between exchange rate updates.</string>
<string>APP_KEY</string>
</array>
<key>version</key>
<string>3.1</string>
<string>3.2</string>
<key>webaddress</key>
<string></string>
</dict>
Expand Down

0 comments on commit 384fc3a

Please sign in to comment.