1 /**
2  * Copyright: Copyright (c) 2010-2011 Jacob Carlborg. All rights reserved.
3  * Authors: Jacob Carlborg
4  * Version: Initial created: Nov 8, 2010
5  * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0)
6  */
7 module dvm.commands.Command;
8 
9 import dvm.dvm._;
10 import mambo.core..string;
11 import Path = dvm.io.Path;
12 
13 abstract class Command
14 {
15     string name;
16     string summary;
17 
18     protected Args args;
19     protected Options options;
20 
21     this () {}
22 
23     this (string name, string summary = "")
24     {
25         this.name = name;
26         this.summary = summary;
27         options = Options.instance;
28     }
29 
30     abstract void execute ();
31 
32     void invoke (string[] args ...)
33     {
34         this.args.args = args;
35         execute_;
36     }
37 
38     void invoke (Args args)
39     {
40         this.args = args;
41         execute_;
42     }
43 
44     private void execute_ ()
45     {
46         deleteTmpDirectory;
47         execute;
48     }
49 
50     private void deleteTmpDirectory ()
51     {
52         if (Path.exists(options.path.tmp))
53             Path.remove(options.path.tmp, true);
54     }
55 }
56 
57 private struct Args
58 {
59     string[] args;
60 
61     string opIndex (size_t index)
62     {
63         if (index > args.length - 1 && empty)
64             throw new MissingArgumentException("Missing argument(s)", __FILE__, __LINE__);
65 
66         return args[index];
67     }
68 
69     string first ()
70     {
71         return opIndex(0);
72     }
73 
74     string first (string arg)
75     {
76         if (empty)
77             args ~= arg;
78 
79         else
80             args[0] = arg;
81 
82         return arg;
83     }
84 
85     string last ()
86     {
87         return opIndex(args.length - 1);
88     }
89 
90     bool empty ()
91     {
92         return args.length == 0;
93     }
94 
95     bool any ()
96     {
97         return !empty;
98     }
99 }