xref: /haiku/src/bin/pkgman/Command.cpp (revision 2b76973fa2401f7a5edf68e6470f3d3210cbcff3)
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 	fName(name),
30 	fShortUsage(shortUsage),
31 	fLongUsage(longUsage),
32 	fCategory(category)
33 {
34 	fShortUsage.ReplaceAll("%command%", fName);
35 	fLongUsage.ReplaceAll("%command%", fName);
36 }
37 
38 
39 Command::~Command()
40 {
41 }
42 
43 
44 void
45 Command::Init(const char* programName)
46 {
47 	fShortUsage.ReplaceAll("%program%", programName);
48 	fLongUsage.ReplaceAll("%program%", programName);
49 }
50 
51 
52 void
53 Command::PrintUsage(bool error) const
54 {
55 	fprintf(error ? stderr : stdout, "%s", fLongUsage.String());
56 }
57 
58 
59 void
60 Command::PrintUsageAndExit(bool error) const
61 {
62 	PrintUsage(error);
63 	exit(error ? 1 : 0);
64 }
65 
66 
67 // #pragma mark - CommandManager
68 
69 
70 /*static*/ CommandManager*
71 CommandManager::Default()
72 {
73 	static CommandManager* manager = new CommandManager;
74 	return manager;
75 }
76 
77 
78 void
79 CommandManager::RegisterCommand(Command* command)
80 {
81 	fCommands.AddItem(command);
82 }
83 
84 
85 void
86 CommandManager::InitCommands(const char* programName)
87 {
88 	for (int32 i = 0; Command* command = fCommands.ItemAt(i); i++)
89 		command->Init(programName);
90 
91 	fCommands.SortItems(&compare_commands_by_name);
92 }
93 
94 
95 void
96 CommandManager::GetCommands(const char* prefix, CommandList& _commands)
97 {
98 	for (int32 i = 0; Command* command = fCommands.ItemAt(i); i++) {
99 		if (command->Name().StartsWith(prefix))
100 			_commands.AddItem(command);
101 	}
102 }
103 
104 
105 void
106 CommandManager::GetCommandsForCategory(const char* category,
107 	CommandList& _commands)
108 {
109 	for (int32 i = 0; Command* command = fCommands.ItemAt(i); i++) {
110 		if (command->Category() == category)
111 			_commands.AddItem(command);
112 	}
113 }
114 
115 
116 CommandManager::CommandManager()
117 	:
118 	fCommands(20, true)
119 {
120 }
121