-
Notifications
You must be signed in to change notification settings - Fork 0
/
prompt.c
107 lines (99 loc) · 2.54 KB
/
prompt.c
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
// Implementation of prompt line
#include "prompt.h"
static char *PS1;
static char *PS2;
char *get_pwd()
{
// For more info about this system function,
// read "man getenv"
char buffer[MAX_PATH_LEN];
char *result;
if(getcwd(buffer, MAX_COMMAND_LEN) == NULL) exit(ENVIRONMENT_FAULT_);
result = (char*)malloc((strlen(buffer) + 1) * sizeof(char));
if(!result) exit(MEM_ALLOC_ERR_);
strcpy(result, buffer);
return result;
}
char *get_pwd_replaced()
{
int i, j;
char *home = getenv("HOME");
char *pwd = get_pwd();
// Allocate spce to hold the replaced sequence
char *replaced = (char*)malloc(MAX_PATH_LEN * sizeof(char));
if(!replaced) exit(MEM_ALLOC_ERR_);
strcpy(replaced, pwd);
// Replacement
for(i = 0; i < strlen(home); i++)
{
// If the two sequeces cannot match, return
if(pwd[i] != home[i]) return replaced;
}
replaced[0] = '~';
for(i = strlen(home), j = 1; i < strlen(pwd); i++, j++)
{
replaced[j] = pwd[i];
}
// End of the string
replaced[j] = 0;
free(pwd);
return replaced;
}
char *get_user()
{
char *result = getenv("USER");
if(!result) exit(ENVIRONMENT_FAULT_);
else return result;
}
char *get_ps1()
{
char *user, *pwd;
// Allocate space if ps1 has not been initialized
if(!PS1) PS1 = (char*)malloc(MAX_PROMPT_LEN * sizeof(char));
if(!PS1) exit(MEM_ALLOC_ERR_);
// HOSTNAME external char* defined in global.c
// Declaration of this variable is in global.h
// Prototype: extern char* HOSTNAME;
// This should be initialized in the init function
if(!HOSTNAME) exit(INIT_ERR_);
// Get the environment variables
user = get_user();
pwd = get_pwd_replaced();
// Write PS1
sprintf(PS1,
// Username
USER_COLOR "%s"
// Hostname
HOSTNAME_COLOR "@%s"
// Default colon
DEFAULT_COLOR ":"
// PWD
PWD_COLOR "%s" "\n"
// Prompt, "myshell> " by default
// See global.h for definition
PROMPT_COLOR PROMPT_STRING
DEFAULT_COLOR,
user, HOSTNAME, pwd);
return PS1;
}
char *get_ps2()
{
// Allocate space if ps2 has not been initialized
if(!PS2)
{
PS2 = (char*)malloc(3 * sizeof(char));
PS2[0] = '>'; PS2[1] = ' '; PS2[2] = 0;
}
if(!PS2) exit(MEM_ALLOC_ERR_);
return PS2;
}
void print_ps1()
{
char *ps1 = get_ps1();
write(STDOUT_FILENO, ps1, strlen(ps1));
}
void print_ps2()
{
char *ps2 = get_ps2();
write(STDOUT_FILENO, ps2, strlen(ps2));
}