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