Skip to content

Commit 92035fe

Browse files
feat: Converts CLI to use expression
1 parent 962e1d9 commit 92035fe

2 files changed

Lines changed: 12 additions & 14 deletions

File tree

Sources/CLI/Convert.swift

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import Units
33

44
struct Convert: ParsableCommand {
55
static var configuration = CommandConfiguration(
6-
abstract: "Convert a measurement to a specified unit.",
6+
abstract: "Convert a measurement expression to a specified unit.",
77
discussion: """
88
Run `unit list` to see the supported unit symbols and names. Unless arguments are wrapped \
99
in quotes, the `*` character may need to be escaped.
@@ -12,20 +12,21 @@ struct Convert: ParsableCommand {
1212
https://github.com/NeedleInAJayStack/Units/blob/main/README.md#serialization
1313
1414
EXAMPLES:
15-
unit convert 1_ft m
15+
unit convert 1ft m
1616
unit convert 1_ft meter
1717
unit convert 5.4_kW\\*hr J
1818
unit convert 5.4e-3_km/s mi/hr
1919
unit convert "12 kg*m/s^2" "N"
20-
unit convert 12_m^1\\*s^-1\\*kg^1 kg\\*m/s
20+
unit convert "8kg * 3m / 2s^2" "N"
2121
"""
2222
)
2323

2424
@Argument(help: """
25-
The measurement to convert. This is a number, followed by a space, followed by a unit \
26-
symbol. For convenience, you may use an underscore `_` to represent the space.
25+
The expression to compute to convert. This must follow the expression parsing rules found \
26+
in https://github.com/NeedleInAJayStack/Units/blob/main/README.md#serialization. \
27+
For convenience, you may use an underscore `_` to represent spaces.
2728
""")
28-
var from: Measurement
29+
var from: Expression
2930

3031
@Argument(help: """
3132
The unit to convert to. This can either be a unit name, a unit symbol, or an equation of \
@@ -34,17 +35,14 @@ struct Convert: ParsableCommand {
3435
var to: Units.Unit
3536

3637
func run() throws {
37-
try print(from.convert(to: to))
38+
try print(from.solve().convert(to: to))
3839
}
3940
}
4041

41-
extension Measurement: ExpressibleByArgument {
42-
public init?(argument: String) {
42+
extension Expression: ExpressibleByArgument {
43+
public convenience init?(argument: String) {
4344
let argument = argument.replacingOccurrences(of: "_", with: " ")
44-
guard let measurement = Measurement(argument) else {
45-
return nil
46-
}
47-
self = measurement
45+
try? self.init(argument)
4846
}
4947
}
5048

Sources/Units/Expression.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/// Represents a mathematical expression of measurements. It supports arithemetic operators, exponents, and sub-expressions.
2-
public class Expression {
2+
public final class Expression {
33
// Implemented as a linked list of ExpressionNodes. This allows us to indicate operators,
44
// and iteratively solve by reducing the list according to the order of operations.
55

0 commit comments

Comments
 (0)