Merge branch 'master' of git://git.gag.com/fw/altos
[fw/altos] / ao-tools / lib / cc-util.c
1 /*
2  * Copyright © 2009 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #define _GNU_SOURCE
19 #include "cc.h"
20 #include <string.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <errno.h>
26
27 char *
28 cc_fullname (char *dir, char *file)
29 {
30         char    *new;
31         int     dlen = strlen (dir);
32         int     flen = strlen (file);
33         int     slen = 0;
34
35         if (dir[dlen-1] != '/')
36                 slen = 1;
37         new = malloc (dlen + slen + flen + 1);
38         if (!new)
39                 return 0;
40         strcpy(new, dir);
41         if (slen)
42                 strcat (new, "/");
43         strcat(new, file);
44         return new;
45 }
46
47 char *
48 cc_basename(char *file)
49 {
50         char *b;
51
52         b = strrchr(file, '/');
53         if (!b)
54                 return file;
55         return b + 1;
56 }
57
58 int
59 cc_mkdir(char *dir)
60 {
61         char    *slash;
62         char    *d;
63         char    *part;
64
65         d = dir;
66         for (;;) {
67                 slash = strchr (d, '/');
68                 if (!slash)
69                         slash = d + strlen(d);
70                 if (!*slash)
71                         break;
72                 part = strndup(dir, slash - dir);
73                 if (!access(part, F_OK))
74                         if (mkdir(part, 0777) < 0)
75                                 return -errno;
76                 free(part);
77                 d = slash + 1;
78         }
79         return 0;
80 }