summaryrefslogtreecommitdiffstats
path: root/src/p_redirs_heredoc.c
blob: 6ba06f150a98cf407d2eb9856a1e75b6036dfeff (plain)
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   p_redirs_heredoc.c                                 :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: rbousset <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/14 17:19:27 by rbousset          #+#    #+#             */
/*   Updated: 2020/02/14 17:19:29 by rbousset         ###   ########lyon.fr   */
/*                                                                            */
/* ************************************************************************** */

#include <libft.h>
#include <stdint.h>
#include <unistd.h>

#include "d_define.h"
#include "m_prompt.h"
#include "s_struct.h"

static void	p_skip_tabs(char *line[], const int8_t redir)
{
	char	*ptr;

	if (redir != -3)
		return ;
	ptr = *line;
	while (ptr[0] != C_NUL && ptr[0] == C_HT)
	{
		(void)ft_memmove(ptr, ptr + 1, (ft_strlen(ptr) + 1) * sizeof(char));
	}
}

static void	p_append_line(char *heredoc[], const char line[])
{
	char	*ptr;

	ptr = *heredoc;
	ft_strlcpy(ptr + ft_strlen(ptr), line, ft_strlen(line) + 1);
	ptr[ft_strlen(ptr) + 1] = C_NUL;
	ptr[ft_strlen(ptr)] = C_LF;
}

char		*p_get_heredoc(const char path[], const int8_t redir, t_msh *msh)
{
	char	*heredoc;
	char	*line;
	int8_t	gnl;

	if ((heredoc = ft_strdup("")) == NULL)
		return (NULL);
	gnl = 1;
	while (gnl > 0)
	{
		if (msh->fd == STDIN_FILENO)
			m_prompt_psx(2, msh);
		gnl = get_next_line(msh->fd, &line);
		p_skip_tabs(&line, redir);
		if (ft_strncmp(path, line, ft_strlen(path) + 1) == 0)
			break ;
		if ((heredoc = ft_nrealloc(heredoc, ft_strlen(heredoc) + 1,
			ft_strlen(heredoc) + ft_strlen(line) + 2)) == NULL)
			break ;
		p_append_line(&heredoc, line);
		ft_memdel((void*)&line);

	}
	if (gnl > 0)
		ft_memdel((void*)&line);
	return (heredoc);
}