xref: /haiku/src/bin/pkgman/Command.cpp (revision 0de25abadc86e260328c6f7c4255acbee8f70d4e)
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 
16 static int
17 compare_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 
26 Command::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 
40 Command::~Command()
41 {
42 }
43 
44 
45 void
46 Command::Init(const char* programName)
47 {
48 	fShortUsage.ReplaceAll("%program%", programName);
49 	fLongUsage.ReplaceAll("%program%", programName);
50 }
51 
52 
53 void
54 Command::PrintUsage(bool error) const
55 {
56 	fprintf(error ? stderr : stdout, "%s", fLongUsage.String());
57 }
58 
59 
60 void
61 Command::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*
72 CommandManager::Default()
73 {
74 	static CommandManager* manager = new CommandManager;
75 	return manager;
76 }
77 
78 
79 void
80 CommandManager::RegisterCommand(Command* command)
81 {
82 	fCommands.AddItem(command);
83 }
84 
85 
86 void
87 CommandManager::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 
96 void
97 CommandManager::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 
106 void
107 CommandManager::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 
117 CommandManager::CommandManager()
118 	:
119 	fCommands(20, true)
120 {
121 }
122