File: init.cpp

package info (click to toggle)
timew 1.1.1+ds.1-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,348 kB
  • sloc: cpp: 22,428; python: 3,612; sh: 111; makefile: 15
file content (307 lines) | stat: -rw-r--r-- 11,833 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 - 2016, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <timew.h>
#include <shared.h>
#include <format.h>
#include <commands.h>
#include <cstring>
#include <unistd.h>
#include <iostream>

////////////////////////////////////////////////////////////////////////////////
bool lightweightVersionCheck (int argc, const char** argv)
{
  if (argc == 2 && std::string (argv[1]) == "--version")
  {
    std::cout << VERSION << '\n';
    return true;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
void initializeEntities (CLI& cli)
{
  // Command entities.
  cli.entity ("command", "cancel");
  cli.entity ("command", "config");
  cli.entity ("command", "continue");
  cli.entity ("command", "delete");
  cli.entity ("command", "diagnostics");
  cli.entity ("command", "export");
  cli.entity ("command", "extensions");
  cli.entity ("command", "fill");
  cli.entity ("command", "gaps");
  cli.entity ("command", "get");
  cli.entity ("command", "help");
  cli.entity ("command", "--help");
  cli.entity ("command", "join");
  cli.entity ("command", "lengthen");
  cli.entity ("command", "move");
  cli.entity ("command", "report");
  cli.entity ("command", "resize");
  cli.entity ("command", "shorten");
  cli.entity ("command", "show");
  cli.entity ("command", "split");
  cli.entity ("command", "start");
  cli.entity ("command", "stop");
  cli.entity ("command", "tag");
  cli.entity ("command", "tags");
  cli.entity ("command", "track");
  cli.entity ("command", "untag");

  // Some command list themselves as extensions, to integrate with the real
  // extensions.
  cli.entity ("extension", "day");
  cli.entity ("extension", "month");
  cli.entity ("extension", "summary");
  cli.entity ("extension", "week");

  // Hint entities.
  cli.entity ("hint", ":adjust");
  cli.entity ("hint", ":blank");
  cli.entity ("hint", ":color");
  cli.entity ("hint", ":day");
  cli.entity ("hint", ":debug");
  cli.entity ("hint", ":fill");
  cli.entity ("hint", ":ids");
  cli.entity ("hint", ":lastmonth");
  cli.entity ("hint", ":lastquarter");
  cli.entity ("hint", ":lastweek");
  cli.entity ("hint", ":lastyear");
  cli.entity ("hint", ":month");
  cli.entity ("hint", ":nocolor");
  cli.entity ("hint", ":quarter");
  cli.entity ("hint", ":quiet");
  cli.entity ("hint", ":week");
  cli.entity ("hint", ":year");
  cli.entity ("hint", ":yes");
  cli.entity ("hint", ":yesterday");
  cli.entity ("hint", ":monday");
  cli.entity ("hint", ":tuesday");
  cli.entity ("hint", ":wednesday");
  cli.entity ("hint", ":thursday");
  cli.entity ("hint", ":friday");
  cli.entity ("hint", ":saturday");
  cli.entity ("hint", ":sunday");
}

////////////////////////////////////////////////////////////////////////////////
void initializeDataAndRules (
  const CLI& cli,
  Database& database,
  Rules& rules)
{
  // Rose tint my world, make me safe from my trouble and pain.
  rules.set ("color", isatty (STDOUT_FILENO) ? "on" : "off");

  // Make common hints available via rules:
  //   :debug   --> debug=on
  //   :quiet   --> verbose=off
  //   :color   --> color=on
  //   :nocolor --> color=off
  //   :yes     --> confirmation=off
  for (auto& arg : cli._args)
  {
    if (arg.hasTag ("HINT"))
    {
      if (arg.attribute ("canonical") == ":debug")   rules.set ("debug",        "on");
      if (arg.attribute ("canonical") == ":quiet")   rules.set ("verbose",      "off");
      if (arg.attribute ("canonical") == ":color")   rules.set ("color",        "on");
      if (arg.attribute ("canonical") == ":nocolor") rules.set ("color",        "off");
      if (arg.attribute ("canonical") == ":yes")     rules.set ("confirmation", "off");
    }
  }

  enableDebugMode (rules.getBoolean ("debug"));

  // The $TIMEWARRIORDB environment variable overrides the default value of
  // ~/.timewarrior‥
  Directory dbLocation;
  char* override = getenv ("TIMEWARRIORDB");
  dbLocation = Directory (override ? override : "~/.timewarrior");

  // If dbLocation exists, but is not readable/writable/executable, error.
  if (dbLocation.exists () &&
      (! dbLocation.readable () ||
       ! dbLocation.writable () ||
       ! dbLocation.executable ()))
  {
    throw format ("Database is not readable at '{1}'", dbLocation._data);
  }

  // If dbLocation does not exist, ask whether it should be created.
  bool shinyNewDatabase = false;
  if (! dbLocation.exists () &&
      (findHint (cli, ":yes") ||
       confirm ("Create new database in " + dbLocation._data + "?")))
  {
    dbLocation.create (0700);
    shinyNewDatabase = true;
  }

  // Create extensions subdirectory if necessary.
  Directory extensions (dbLocation);
  extensions += "extensions";
  if (! extensions.exists ())
    extensions.create (0700);

  // Create data subdirectory if necessary.
  Directory data (dbLocation);
  data += "data";
  if (! data.exists ())
    data.create (0700);

  // Load the configuration data.
  File configFile (dbLocation);
  configFile += "timewarrior.cfg";
  configFile.create (0600);
  rules.load (configFile._data);

  // This value is not written out to disk, as there would be no point. Having
  // located the config file, the 'db' location is already known. This is just
  // for subsequent internal use.
  rules.set ("temp.db", dbLocation._data);

  // Perhaps some subsequent code would like to know this is a new db and
  // possibly a first run.
  if (shinyNewDatabase)
    rules.set ("temp.shiny", 1);

  if (rules.has ("debug.indicator"))
    setDebugIndicator (rules.get ("debug.indicator"));

  if (rules.has ("theme.colors.debug"))
    setDebugColor (Color (rules.get ("theme.colors.debug")));

  // Apply command line overrides.
  for (auto& arg : cli._args)
  {
    if (arg.hasTag ("CONFIG"))
    {
      rules.set (arg.attribute ("name"), arg.attribute ("value"));
      debug (format ("Configuration override {1} = {2}", arg.attribute ("name"), arg.attribute ("value")));
    }
  }

  // Initialize the database (no data read), but files are enumerated.
  database.initialize (data._data);
}

////////////////////////////////////////////////////////////////////////////////
void initializeExtensions (
  CLI& cli,
  const Rules& rules,
  Extensions& extensions)
{
  Directory extDir (rules.get ("temp.db"));
  extDir += "extensions";

  extensions.initialize (extDir._data);

  // Add extensions as CLI entities.
  for (auto& ext : extensions.all ())
    cli.entity ("extension", File (ext).name ());

  // Extensions have a debug mode.
  if (rules.getBoolean ("debug"))
    extensions.debug ();
}

////////////////////////////////////////////////////////////////////////////////
int dispatchCommand (
  const CLI& cli,
  Database& database,
  Rules& rules,
  const Extensions& extensions)
{
  int status {0};

  // Debug output.
  if (rules.getBoolean ("debug"))
    std::cout << cli.dump () << '\n';

  // Dispatch to the right command function.
  std::string command = cli.getCommand ();
  if (command != "")
  {
    // These signatures are expected to be all different, therefore no
    // command to fn mapping.
         if (command == "cancel")      status = CmdCancel        (     rules, database            );
    else if (command == "config")      status = CmdConfig        (cli, rules, database            );
    else if (command == "continue")    status = CmdContinue      (cli, rules, database            );
    else if (command == "day")         status = CmdChartDay      (cli, rules, database            );
    else if (command == "delete")      status = CmdDelete        (cli, rules, database            );
    else if (command == "diagnostics") status = CmdDiagnostics   (     rules, database, extensions);
    else if (command == "export")      status = CmdExport        (cli, rules, database            );
    else if (command == "extensions")  status = CmdExtensions    (     rules,           extensions);
/*
    else if (command == "fill")        status = CmdFill          (cli, rules, database            );
*/
    else if (command == "gaps")        status = CmdGaps          (cli, rules, database            );
    else if (command == "get")         status = CmdGet           (cli, rules, database            );
    else if (command == "help" ||
             command == "--help")      status = CmdHelp          (cli,                  extensions);
    else if (command == "join")        status = CmdJoin          (cli, rules, database            );
    else if (command == "lengthen")    status = CmdLengthen      (cli, rules, database            );
    else if (command == "month")       status = CmdChartMonth    (cli, rules, database            );
    else if (command == "move")        status = CmdMove          (cli, rules, database            );
    else if (command == "report")      status = CmdReport        (cli, rules, database, extensions);
    else if (command == "resize")      status = CmdResize        (cli, rules, database            );
    else if (command == "shorten")     status = CmdShorten       (cli, rules, database            );
    else if (command == "show")        status = CmdShow          (     rules                      );
    else if (command == "split")       status = CmdSplit         (cli, rules, database            );
    else if (command == "start")       status = CmdStart         (cli, rules, database            );
    else if (command == "stop")        status = CmdStop          (cli, rules, database            );
    else if (command == "summary")     status = CmdSummary       (cli, rules, database            );
    else if (command == "tag")         status = CmdTag           (cli, rules, database            );
    else if (command == "tags")        status = CmdTags          (cli, rules, database            );
    else if (command == "track")       status = CmdTrack         (cli, rules, database            );
    else if (command == "untag")       status = CmdUntag         (cli, rules, database            );
    else if (command == "week")        status = CmdChartWeek     (cli, rules, database            );
    else                               status = CmdReport        (cli, rules, database, extensions);
  }
  else
  {
    auto words = cli.getWords ();

    if (words.size () > 0)
    {
      throw format ("'{1}' is not a timew command. See 'timew help'.", words[0]);
    }
    else
    {
      status = CmdDefault (rules, database);
    }
  }

  return status;
}

////////////////////////////////////////////////////////////////////////////////