1/*
2 * Copyright 2013, Haiku, Inc. All Rights Reserved.
3 * Distributed under the terms of the MIT License.
4 *
5 * Authors:
6 *		Ingo Weinhold <ingo_weinhold@gmx.de>
7 */
8
9
10#include "Command.h"
11
12#include <stdio.h>
13#include <stdlib.h>
14
15
16static int
17compare_commands_by_name(const Command* a, const Command* b)
18{
19	return a->Name().Compare(b->Name());
20}
21
22
23// #pragma mark - Command
24
25
26Command::Command(const BString& name, const BString& shortUsage,
27	const BString& longUsage, const BString& category)
28	:
29	fCommonOptions(),
30	fName(name),
31	fShortUsage(shortUsage),
32	fLongUsage(longUsage),
33	fCategory(category)
34{
35	fShortUsage.ReplaceAll("%command%", fName);
36	fLongUsage.ReplaceAll("%command%", fName);
37}
38
39
40Command::~Command()
41{
42}
43
44
45void
46Command::Init(const char* programName)
47{
48	fShortUsage.ReplaceAll("%program%", programName);
49	fLongUsage.ReplaceAll("%program%", programName);
50}
51
52
53void
54Command::PrintUsage(bool error) const
55{
56	fprintf(error ? stderr : stdout, "%s", fLongUsage.String());
57}
58
59
60void
61Command::PrintUsageAndExit(bool error) const
62{
63	PrintUsage(error);
64	exit(error ? 1 : 0);
65}
66
67
68// #pragma mark - CommandManager
69
70
71/*static*/ CommandManager*
72CommandManager::Default()
73{
74	static CommandManager* manager = new CommandManager;
75	return manager;
76}
77
78
79void
80CommandManager::RegisterCommand(Command* command)
81{
82	fCommands.AddItem(command);
83}
84
85
86void
87CommandManager::InitCommands(const char* programName)
88{
89	for (int32 i = 0; Command* command = fCommands.ItemAt(i); i++)
90		command->Init(programName);
91
92	fCommands.SortItems(&compare_commands_by_name);
93}
94
95
96void
97CommandManager::GetCommands(const char* prefix, CommandList& _commands)
98{
99	for (int32 i = 0; Command* command = fCommands.ItemAt(i); i++) {
100		if (command->Name().StartsWith(prefix))
101			_commands.AddItem(command);
102	}
103}
104
105
106void
107CommandManager::GetCommandsForCategory(const char* category,
108	CommandList& _commands)
109{
110	for (int32 i = 0; Command* command = fCommands.ItemAt(i); i++) {
111		if (command->Category() == category)
112			_commands.AddItem(command);
113	}
114}
115
116
117CommandManager::CommandManager()
118	:
119	fCommands(20, true)
120{
121}
122