Esempio n. 1
0
static void vdtree_row_expanded(GtkTreeView *treeview, GtkTreeIter *iter, GtkTreePath *tpath, gpointer data)
{
	ViewDir *vd = data;
	GtkTreeModel *store;
	NodeData *nd = NULL;
	FileData *fd;

	gtk_tree_view_set_tooltip_column(treeview, DIR_COLUMN_LINK);

	vdtree_populate_path_by_iter(vd, iter, FALSE, NULL);
	store = gtk_tree_view_get_model(GTK_TREE_VIEW(treeview));

	gtk_tree_model_get_iter(store, iter, tpath);
	gtk_tree_model_get(store, iter, DIR_COLUMN_POINTER, &nd, -1);

	fd = (nd) ? nd->fd : NULL;
	if (fd && islink(fd->path))
		{
		vdtree_icon_set_by_iter(vd, iter, vd->pf->link);
		}
	else
		{
		vdtree_icon_set_by_iter(vd, iter, vd->pf->open);
		}
}
Esempio n. 2
0
str *_resolve_link(str *path) {
    /**
    Internal helper function.  Takes a path and follows symlinks
    until we either arrive at something that isn't a symlink, or
    encounter a path we've seen before (meaning that there's a loop).
    */
    list<str *> *paths_seen;
    str *dir, *resolved;

    paths_seen = (new list<str *>());

    while(islink(path)) {
        if (paths_seen->__contains__(path)) {
            return 0;
        }
        paths_seen->append(path);
        resolved = __os__::readlink(path);
        if ((!isabs(resolved))) {
            dir = dirname(path);
            path = normpath(join(2, dir, resolved));
        }
        else {
            path = normpath(resolved);
        }
    }
    return path;
}
Esempio n. 3
0
File *getfinaltarget(File *file)
{
    Map *linkmap = newmap();
    if (!linkmap) {
        errorf("Out of memory?\n");
        return NULL;
    }
    File *target = NULL;
    while (isstat(file) && islink(file)) {
        target = gettarget(file);
        if (!target) {
            errorf("Cannot determine target of %s for %s\n", getname(file));
            break;
        }
        if (inmap(linkmap, getinode(target))) {
            errorf("Symlink loop in %s\n", getname(file));
            /* no file to stat, but want to print the name field */
            target = NULL;
            break;
        } else {
            set(linkmap, (uintmax_t)getinode(target), NULL);
        }
        file = target;
    }
    freemap(linkmap);
    return target;
}
Esempio n. 4
0
str *realpath(str *filename) {
    /**
    Return the canonical path of the specified filename, eliminating any
    symbolic links encountered in the path.
    */
    list<str *> *bits;
    str *component, *newpath, *resolved;
    __ss_int __40, __41, i;

    if (isabs(filename)) {
        bits = ((new list<str *>(1, const_4)))->__add__((filename->split(const_4))->__slice__(1, 1, 0, 0));
    }
    else {
        bits = filename->split(const_4);
    }

    FAST_FOR(i,2,(len(bits)+1),1,40,41)
        component = joinl(bits->__slice__(3, 0, i, 0));
        if (islink(component)) {
            resolved = _resolve_link(component);
            if ((resolved==0)) {
                return abspath(joinl(((new list<str *>(1, component)))->__add__(bits->__slice__(1, i, 0, 0))));
            }
            else {
                newpath = joinl(((new list<str *>(1, resolved)))->__add__(bits->__slice__(1, i, 0, 0)));
                return realpath(newpath);
            }
        }
    END_FOR

    return abspath(filename);
}
Esempio n. 5
0
File: tar.c Progetto: aahud/harvey
/*
 * return the number of bytes recorded in the archive.
 */
static Off
arsize(Hdr *hp)
{
	if(isdir(hp) || islink(hp->linkflag))
		return 0;
	return hdrsize(hp);
}
Esempio n. 6
0
/*
 * Return a string (dynamically allocated) with the name of the file to which
 * LINK is symlinked.
 */
char *xreadlink (const char *link)
{
    char *file = NULL;
    char *tfile;
    int buflen = 128;
    int link_name_len;

    if (!islink (link))
        return NULL;

    /* Get the name of the file to which `from' is linked.
       FIXME: what portability issues arise here?  Are readlink &
       ENAMETOOLONG defined on all systems? -twp */
    do
    {
        file = (char*)xrealloc (file, buflen);
        link_name_len = readlink (link, file, buflen - 1);
        buflen *= 2;
    }
    while (link_name_len < 0 && errno == ENAMETOOLONG);

    if (link_name_len < 0)
        error (1, errno, "cannot readlink %s", link);

    file[link_name_len] = '\0';

    tfile = xstrdup (file);
    xfree (file);

    return tfile;
}
Esempio n. 7
0
int main(int argc,char *argv[]) {
	bool follow = false;

	int opt;
	while((opt = getopt(argc,argv,"f")) != -1) {
		switch(opt) {
			case 'f': follow = true; break;
			default:
				usage(argv[0]);
		}
	}
	if(optind >= argc)
		usage(argv[0]);

	for(int i = optind; i < argc; ++i) {
		char tmp[MAX_PATH_LEN];
		if(follow) {
			if(canonpath(tmp,sizeof(tmp),argv[i]) < 0) {
				printe("readlink for '%s' failed",argv[i]);
				continue;
			}
			puts(tmp);
		}
		else {
			if(!islink(argv[i]))
				printe("'%s' is no symbolic link",argv[i]);
			else if(readlink(argv[i],tmp,sizeof(tmp)) < 0)
				printe("readlink for '%s' failed",argv[i]);
			else
				puts(tmp);
		}
	}
	return EXIT_SUCCESS;
}
Esempio n. 8
0
gboolean vdtree_press_key_cb(GtkWidget *widget, GdkEventKey *event, gpointer data)
{
	ViewDir *vd = data;
	GtkTreePath *tpath;
	GtkTreeIter iter;
	FileData *fd = NULL;

	gtk_tree_view_get_cursor(GTK_TREE_VIEW(vd->view), &tpath, NULL);
	if (tpath)
		{
		GtkTreeModel *store;
		NodeData *nd;

		store = gtk_tree_view_get_model(GTK_TREE_VIEW(widget));
		gtk_tree_model_get_iter(store, &iter, tpath);
		gtk_tree_model_get(store, &iter, DIR_COLUMN_POINTER, &nd, -1);

		gtk_tree_path_free(tpath);

		fd = (nd) ? nd->fd : NULL;
		}

	switch (event->keyval)
		{
		case GDK_KEY_Menu:
			vd->click_fd = fd;
			vd_color_set(vd, vd->click_fd, TRUE);

			vd->popup = vd_pop_menu(vd, vd->click_fd);
			gtk_menu_popup(GTK_MENU(vd->popup), NULL, NULL, vd_menu_position_cb, vd, 0, GDK_CURRENT_TIME);

			return TRUE;
			break;
		case GDK_KEY_plus:
		case GDK_KEY_Right:
		case GDK_KEY_KP_Add:
			if (fd)
				{
				vdtree_populate_path_by_iter(vd, &iter, FALSE, vd->dir_fd);

				if (islink(fd->path))
					{
					vdtree_icon_set_by_iter(vd, &iter, vd->pf->link);
					}
				else
					{
					vdtree_icon_set_by_iter(vd, &iter, vd->pf->open);
					}
				}
			break;
		}

	return FALSE;
}
Esempio n. 9
0
File: bin.c Progetto: bitursa/maos
/*
  Process the input file name and return file names that can be open to
  read/write. If the file name does not end with .bin or .bin.gz it will add to
  the end .bin or .bin.gz depending on the value of defaultgzip. For read only
  access, it will also look into the path for files.
*/
static char* procfn(const char *fn, const char *mod, const int defaultgzip) {
    char *fn2;
    if(fn[0]=='~') {
        fn2=malloc(strlen(HOME)+strlen(fn)+16);
        strcpy(fn2,HOME);
        strcat(fn2,fn+1);
    } else {
        fn2=malloc(strlen(fn)+16);
        strcpy(fn2,fn);
    }
    /*If there is no recognized suffix, add .bin in the end. */
    if(!check_suffix(fn2,".bin")  && !check_suffix(fn2, ".bin.gz")
            && !check_suffix(fn2,".fits") && !check_suffix(fn2, ".fits.gz")) {
        strncat(fn2, ".bin", 4);
    }
    if(mod[0]=='r') {
        char *fnr=NULL;
        if(!(fnr=search_file(fn2))) { /*If does not exist. */
            if(!check_suffix(fn2, ".gz")) {
                /*does not end with .gz, add gz*/
                strncat(fn2, ".gz", 3);
            } else if (check_suffix(fn, ".gz")) {
                /*ended with gz, remove .gz*/
                fn2[strlen(fn2)-3]='\0';
            }
            fnr=search_file(fn2);
        }
        free(fn2);
        fn2=fnr;
        if(!fnr) {

        }
    } else if (mod[0]=='w' || mod[0]=='a') {
        if(disable_save) { //When saving is disabled, allow writing to cache folder.
            char fncache[PATH_MAX];
            snprintf(fncache, PATH_MAX, "%s/.aos/cache", HOME);
            if(mystrcmp(fn2, fncache)) {
                warning("Saving is disabled for %s.\n", fn2);
                free(fn2);
                fn2=0;
            }
        }
        if(fn2 && islink(fn2)) { /*remove old file to avoid write over a symbolic link. */
            if(remove(fn2)) {
                error("Failed to remove %s\n", fn2);
            }
        }
    } else {
        error("Invalid mode\n");
    }
    return fn2;
}
Esempio n. 10
0
inline Try<dev_t> dev(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  struct _stat s;

  if (follow == DO_NOT_FOLLOW_SYMLINK && islink(path)) {
    return Error("lstat not supported for symlink '" + path + "'");
  }

  if (::_stat(path.c_str(), &s) < 0) {
    return ErrnoError("Error invoking stat for '" + path + "'");
  }

  return s.st_dev;
}
Esempio n. 11
0
inline bool isdir(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  struct _stat s;

  // A symlink itself is not a directory.
  // If it's not a link, we ignore `follow`.
  if (follow == DO_NOT_FOLLOW_SYMLINK && islink(path)) {
    return false;
  }

  if (::_stat(path.c_str(), &s) < 0) {
    return false;
  }

  return S_ISDIR(s.st_mode);
}
Esempio n. 12
0
inline bool isfile(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  struct _stat s;

  // A symlink itself is a file, but not a regular file.
  // On POSIX, this check is done with `S_IFREG`, which
  // returns false for symbolic links.
  // If it's not a link, we ignore `follow`.
  if (follow == DO_NOT_FOLLOW_SYMLINK && islink(path)) {
    return false;
  }

  if (::_stat(path.c_str(), &s) < 0) {
    return false;
  }

  return S_ISREG(s.st_mode);
}
Esempio n. 13
0
static void vdtree_expand_by_iter(ViewDir *vd, GtkTreeIter *iter, gboolean expand)
{
	GtkTreeModel *store;
	GtkTreePath *tpath;
	NodeData *nd;
	FileData *fd = NULL;

	store = gtk_tree_view_get_model(GTK_TREE_VIEW(vd->view));
	tpath = gtk_tree_model_get_path(store, iter);

	if (expand)
		{
		/* block signal handler, icon is set here, the caller of vdtree_expand_by_iter must make sure
		   that the iter is populated */
		g_signal_handlers_block_by_func(G_OBJECT(vd->view), vdtree_row_expanded, vd);
		gtk_tree_view_expand_row(GTK_TREE_VIEW(vd->view), tpath, FALSE);
		gtk_tree_model_get(store, iter, DIR_COLUMN_POINTER, &nd, -1);
		fd = (nd) ? nd->fd : NULL;

		if (fd && islink(fd->path))
			{
			vdtree_icon_set_by_iter(vd, iter, vd->pf->link);
			}
		else
			{
			vdtree_icon_set_by_iter(vd, iter, vd->pf->open);
			}

		g_signal_handlers_unblock_by_func(G_OBJECT(vd->view), vdtree_row_expanded, vd);
		}
	else
		{
		/* signal handler vdtree_row_collapsed is called, it updates the icon */
		gtk_tree_view_collapse_row(GTK_TREE_VIEW(vd->view), tpath);
		}
	gtk_tree_path_free(tpath);
}
Esempio n. 14
0
File *gettarget(File *file)
{
    if (!file) {
        errorf("file is NULL\n");
        return NULL;
    }
    if (!islink(file)) {
        errorf("%s is not a symlink\n", file->path);
        return NULL;
    }
    if (!file->target) {
        char targetpath[PATH_MAX];
        /* note: readlink(3p) not readlink(2) */
        errno = 0;
        int nchars = readlink(file->path, targetpath, sizeof(targetpath)-1);
        if (nchars == -1) {
            errorf("Error getting symlink target: %s\n", strerror(errno));
            return NULL;
        } else if (nchars == sizeof(targetpath)-1) {
            errorf("Symlink target too long for buffer\n");
            return NULL;
        }
        targetpath[nchars] = '\0';
        char *dir = getdirname(file);
        if (dir == NULL) {
            errorf("getdirname returned NULL\n");
            return NULL;
        }
        file->target = newfile(dir, targetpath);
        free(dir);
        if (file->target == NULL) {
            errorf("newfile returned NULL\n");
            return NULL;
        }
    }
    return file->target;
}
Esempio n. 15
0
					/* Fall through . . */
				case 107:
					if (tolower (ch) == 'h') {
						state = 1;
						start = n;
					} else
						state = ST_INITIAL;
					break;
				case ST_START_FOUND:
					if (isspace ((int) ((unsigned char) ch)) ||
					    (ch == '"') ||
					    (ch == '>')) {
						end = n;
						state = ST_END_FOUND;
					}
					break;
				}
# undef		CHK
# undef		CCHK					
			} else {
				if (state == ST_START_FOUND) {
					end = n;
					state = ST_END_FOUND;
				} else
					state = ST_INITIAL;
			}
			n += clen;
		} else {
			if (state == ST_START_FOUND) {
				end = n;
				state = ST_END_FOUND;
			}
			++n;
		}
		if (state == ST_END_FOUND) {
			int	ulen, m, o;

			ulen = end - start;
			for (m = 0; m < blockmail -> url_count; ++m)
				if ((blockmail -> url[m] -> usage & mask) &&
				    (blockmail -> url[m] -> dlen == ulen) &&
				    (! xmlStrncmp (blockmail -> url[m] -> dptr, cont + start, ulen)))
					break;
			if (m < blockmail -> url_count) {
				if (lstore < start)
					xmlBufferAdd (block -> out, cont + lstore, start - lstore);
				for (o = 0; o < rec -> url_count; ++o)
					if (rec -> url[o] -> uid == blockmail -> url[m] -> uid)
						break;
				if (o < rec -> url_count)
					xmlBufferAdd (block -> out, rec -> url[o] -> dptr, rec -> url[o] -> dlen);
				lstore = end;
				changed = true;
			}
			state = ST_INITIAL;
		}
	}
	if (changed) {
		if (lstore < len)
			xmlBufferAdd (block -> out, cont + lstore, len - lstore);
		SWAP (block);
	}
	return true;
}/*}}}*/
static bool_t
collect_links (blockmail_t *blockmail, block_t *block, links_t *links) /*{{{*/
{
	bool_t		rc;
	int		n, clen;
	int		len;
	const xmlChar	*cont;
	int		start;
	
	rc = true;
	len = xmlBufferLength (block -> in);
	cont = xmlBufferContent (block -> in);
	for (n = 0; rc && (n < len); ) {
		clen = xmlCharLength (cont[n]);
		if ((clen == 1) && (cont[n] == 'h')) {
			start = n;
			++n;
			if ((n + 3 < len) && (cont[n] == 't') && (cont[n + 1] == 't') && (cont[n + 2] == 'p')) {
				n += 3;
				if ((n + 1 < len) && (cont[n] == 's'))
					++n;
				if ((n + 3 < len) && (cont[n] == ':') && (cont[n + 1] == '/') && (cont[n + 2] == '/')) {
					n += 3;
					while ((n < len) && (xmlCharLength (cont[n]) == 1) &&
					       (cont[n] != '"') && (cont[n] != '<') && (cont[n] != '>') &&
					       (! isspace (cont[n])))
						++n;
					rc = links_nadd (links, (const char *) (cont + start), n - start);
				}
			}
		} else
			n += clen;
	}
	return rc;
}/*}}}*/
static int
find_top (const xmlChar *cont, int len) /*{{{*/
{
	int		pos;
	int		state;
	int		n;
	int		clen;
	unsigned char	ch;

	for (pos = -1, state = 0, n = 0; (n < len) && (pos == -1); ) {
		clen = xmlCharLength (cont[n]);
		if (clen > 1)
			state = 0;
		else {
			ch = cont[n];

			switch (state) {
			case 0:
				if (ch == '<')
					state = 1;
				break;
			case 1:
				if ((ch == 'b') || (ch == 'B'))
					state = 2;
				else if (ch == '>')
					state = 0;
				else if (! isspace (ch))
					state = 100;
				break;
			case 2:
				if ((ch == 'o') || (ch == 'O'))
					state = 3;
				else if (ch == '>')
					state = 0;
				else
					state = 100;
				break;
			case 3:
				if ((ch == 'd') || (ch == 'D'))
					state = 4;
				else if (ch == '>')
					state = 0;
				else
					state = 100;
				break;
			case 4:
				if ((ch == 'y') || (ch == 'Y'))
					state = 5;
				else if (ch == '>')
					state = 0;
				else
					state = 100;
				break;
			case 5:
				if (ch == '>') {
					pos = n + clen;
					state = 0;
				} else if (isspace (ch))
					state = 6;
				else
					state = 100;
				break;
			case 6:
				if (ch == '>') {
					pos = n + clen;
					state = 0;
				}
# ifdef		STRICT				
				else if (ch == '"')
					state = 7;
				break;
			case 7:
				if (ch == '"')
					state = 6;
# endif		/* STRICT */
				break;
			case 100:
				if (ch == '>')
					state = 0;
				break;
			}
		}
		n += clen;
	}
	return pos;
}/*}}}*/
static int
find_bottom (const xmlChar *cont, int len) /*{{{*/
{
	int	pos;
	int	last;
	int	m;
	int	bclen;
	
	for (pos = -1, last = len, m = len - 1; (m >= 0) && (pos == -1); ) {
		bclen = xmlCharLength (cont[m]);
		if ((bclen == 1) && (cont[m] == '<')) {
			int		n;
			int		state;
			int		clen;
			unsigned char	ch;

			for (n = m + bclen, state = 1; (n < last) && (state > 0) && (state != 99); ) {
				clen = xmlCharLength (cont[n]);
				if (clen != 1)
					state = 0;
				else {
					ch = cont[n];
					switch (state) {
					case 1:
						if (ch == '/')
							state = 2;
						else if (! isspace (ch))
							state = 0;
						break;
					case 2:
						if ((ch == 'b') || (ch == 'B'))
							state = 3;
						else if (! isspace (ch))
							state = 0;
						break;
					case 3:
						if ((ch == 'o') || (ch == 'O'))
							state = 4;
						else
							state = 0;
						break;
					case 4:
						if ((ch == 'd') || (ch == 'D'))
							state = 5;
						else
							state = 0;
						break;
					case 5:
						if ((ch == 'y') || (ch == 'Y'))
							state = 6;
						else
							state = 0;
						break;
					case 6:
						if ((ch == '>') || isspace (ch))
							state = 99;
						else
							state = 0;
						break;
					}
				}
				n += clen;
			}
			if (state == 99)
				pos = m;
		} else if ((bclen == 1) && (cont[m] == '>'))
			last = m + bclen;
		m -= bclen;
	}
	return pos;
}/*}}}*/
static bool_t
add_onepixellog_image (blockmail_t *blockmail, receiver_t *rec, block_t *block, opl_t opl) /*{{{*/
{
	bool_t		rc;
	const xmlChar	tname[] = "[agnONEPIXEL]";
	int		tlen = sizeof (tname) - 1;
	tag_t		*opltag;
	
	rc = true;
	for (opltag = rec -> tag; opltag; opltag = opltag -> next)
		if (tag_match (opltag, tname, tlen))
			break;
	if (opltag && opltag -> value) {
		int		pos;
		int		len;
		const xmlChar	*cont;
		
		pos = -1;
		len = xmlBufferLength (block -> in);
		cont = xmlBufferContent (block -> in);
		switch (opl) {
		case OPL_None:
			break;
		case OPL_Top:
			pos = find_top (cont, len);
			if (pos == -1)
				pos = 0;
			break;
		case OPL_Bottom:
			pos = find_bottom (cont, len);
			if (pos == -1)
				pos = len;
			break;
		}
		if (pos != -1) {
			const xmlChar	lprefix[] = "<img src=\"";
			const xmlChar	lpostfix[] = "\" alt=\"\" border=\"0\" height=\"1\" width=\"1\">";
			
			xmlBufferEmpty (block -> out);
			if (pos > 0)
				xmlBufferAdd (block -> out, cont, pos);
			xmlBufferAdd (block -> out, lprefix, sizeof (lprefix) - 1);
			xmlBufferAdd (block -> out, xmlBufferContent (opltag -> value), xmlBufferLength (opltag -> value));
			xmlBufferAdd (block -> out, lpostfix, sizeof (lpostfix) - 1);
			if (pos < len)
				xmlBufferAdd (block -> out, cont + pos, len - pos);
			SWAP (block);
		}
	}
	return rc;
}/*}}}*/
static
# ifdef		__OPTIMIZE__
inline
# endif		/* __OPTIMIZE__ */
bool_t
islink (const xmlChar *str, int len) /*{{{*/
{
	int	n, state, clen;
	
	for (n = 0, state = 1; (n < len) && state; ) {
		clen = xmlCharLength (str[n]);
		if (clen != 1)
			return false;
		switch (state) {
		default: /* should NEVER happen */
			return false;
		case 1:	/* check for http:// https:// and mailto: */
			if ((str[n] == 'h') || (str[n] == 'H'))
				++state;
			else if ((str[n] == 'm') || (str[n] == 'M'))
				state = 100;
			else
				return false;
			break;
		case 2:
			if ((str[n] == 't') || (str[n] == 'T'))
				++state;
			else
				return false;
			break;
		case 3:
			if ((str[n] == 't') || (str[n] == 'T'))
				++state;
			else
				return false;
			break;
		case 4:
			if ((str[n] == 'p') || (str[n] == 'P'))
				++state;
			else
				return false;
			break;
		case 5:
			if ((str[n] == 's') || (str[n] == 'S'))
				++state;
			else if (str[n] == ':')
				state += 2;
			else
				return false;
			break;
		case 6:
			if (str[n] == ':')
				++state;
			else
				return false;
			break;
		case 7:
			if (str[n] == '/')
				++state;
			else
				return false;
			break;
		case 8:
			if (str[n] == '/')
				state = 0;
			else
				return false;
			break;
		case 100:
			if ((str[n] == 'a') || (str[n] == 'A'))
				++state;
			else
				return false;
			break;
		case 101:
			if ((str[n] == 'i') || (str[n] == 'I'))
				++state;
			else
				return false;
			break;
		case 102:
			if ((str[n] == 'l') || (str[n] == 'L'))
				++state;
			else
				return false;
			break;
		case 103:
			if ((str[n] == 't') || (str[n] == 'T'))
				++state;
			else
				return false;
			break;
		case 104:
			if ((str[n] == 'o') || (str[n] == 'O'))
				++state;
			else
				return false;
			break;
		case 105:
			if (str[n] == ':')
				state = 0;
			else
				return false;
			break;
		}
		n += clen;
	}
	return (! state) ? true : false;
}/*}}}*/
static bool_t
modify_linelength (blockmail_t *blockmail, block_t *block, blockspec_t *bspec) /*{{{*/
{
# define	DOIT_NONE	(0)
# define	DOIT_RESET	(1 << 0)
# define	DOIT_NEWLINE	(1 << 1)
# define	DOIT_IGNORE	(1 << 2)
# define	DOIT_SKIP	(1 << 3)	
	int		n;
	int		len;
	const xmlChar	*cont;
	int		spos, slen;
	int		space, dash;
	int		spchr, dachr;
	int		inspace, spacecount;
	int		llen, wordstart;
	int		doit;
	int		skipcount;
	bool_t		changed;

	xmlBufferEmpty (block -> out);
	len = xmlBufferLength (block -> in);
	cont = xmlBufferContent (block -> in);
	spos = 0;
	space = -1;
	dash = -1;
	spchr = -1;
	dachr = -1;
	inspace = 0;
	spacecount = 0;
	llen = 0;
	wordstart = 0;
	doit = DOIT_NONE;
	skipcount = 0;
	changed = false;
	for (n = 0; n < len; ) {
		if ((cont[n] == '\r') || (cont[n] == '\n')) {
			doit = DOIT_RESET;
			if (inspace && (spchr + inspace == llen)) {
				n = space;
				doit |= DOIT_NEWLINE | DOIT_IGNORE | DOIT_SKIP;
				skipcount = inspace + 1;
			}
		} else {
			if ((cont[n] == ' ') || (cont[n] == '\t')) {
				if (! inspace++) {
					space = n;
					spchr = llen;
				}
				spacecount = inspace;
			} else {
				if (inspace) {
					inspace = 0;
					wordstart = n;
				}
				if ((cont[n] == '-') && (llen > 2) &&
				    ((spchr == -1) || (llen - spchr > 2)) &&
				    (! islink (cont + wordstart, n - wordstart))) {
					dash = n;
					dachr = llen;
				}
			}
			if (++llen >= bspec -> linelength)
				if ((space != -1) || (dash != -1)) {
					if (space > dash) {
						if (! inspace) {
							n = space;
							doit = DOIT_RESET | DOIT_NEWLINE | DOIT_IGNORE | DOIT_SKIP;
							skipcount = spacecount;
						}
					} else {
						n = dash;
						doit = DOIT_RESET | DOIT_NEWLINE;
					}
				}
		}
		if (! (doit & DOIT_IGNORE))
			n += xmlCharLength (cont[n]);
		if (doit) {
			slen = n - spos;
			if (slen > 0)
				xmlBufferAdd (block -> out, cont + spos, slen);
			if (doit & DOIT_NEWLINE) {
				xmlBufferAdd (block -> out, bspec -> linesep, bspec -> seplength);
				changed = true;
			}
			if (doit & DOIT_SKIP) {
				while ((skipcount-- > 0) && (n < len))
					n += xmlCharLength (cont[n]);
				changed = true;
			}
			spos = n;
			space = -1;
			dash = -1;
			spchr = -1;
			dachr = -1;
			inspace = 0;
			spacecount = 0;
 			llen = 0;
			wordstart = n;
			doit = DOIT_NONE;
		}
	}
	if (changed) {
		if (spos < len)
			xmlBufferAdd (block -> out, cont + spos, len - spos);
		SWAP (block);
	}
	return true;
# undef		DOIT_NONE
# undef		DOIT_RESET
# undef		DOIT_NEWLINE
# undef		DOIT_IGNORE
# undef		DOIT_SKIP
}/*}}}*/
Esempio n. 16
0
/*
 * Copies "from" to "to", decompressing "from" on the fly
 */
int copy_and_unzip_file (const char *from, const char *to, int force_overwrite, int must_exist)
{
    struct stat sb;
    struct utimbuf t;
    int fdin, fdout;
    z_stream zstr = {0};
    int zstatus;
    char buf[BUFSIZ*10];
    char zbuf[BUFSIZ*20];
    int n;
#ifdef UTIME_EXPECTS_WRITABLE
    int change_it_back = 0;
#endif

    TRACE(1,"copy_and_unzip(%s,%s)",PATCH_NULL(from),PATCH_NULL(to));
    if (noexec)
        return 0;

    /* If the file to be copied is a link or a device, then just create
       the new link or device appropriately. */
    if (islink (from))
    {
        char *source = xreadlink (from);
        symlink (source, to);
        xfree (source);
        return 0;
    }

    if (isdevice (from))
    {
#if defined(HAVE_MKNOD) && defined(HAVE_STRUCT_STAT_ST_RDEV)
        if (stat (from, &sb) < 0)
            error (1, errno, "cannot stat %s", fn_root(from));
        mknod (to, sb.st_mode, sb.st_rdev);
#else
        error (1, 0, "cannot copy device files on this system (%s)", fn_root(from));
#endif
    }
    else
    {
        /* Not a link or a device... probably a regular file. */
        if ((fdin = CVS_OPEN (from, O_RDONLY)) < 0)
        {
            if(must_exist)
                error (1, errno, "cannot open %s for copying", fn_root(from));
            else
                return -1;
        }
        if (fstat (fdin, &sb) < 0)
        {
            if(must_exist)
                error (1, errno, "cannot fstat %s", fn_root(from));
            else
            {
                close(fdin);
                return -1;
            }
        }
        if (force_overwrite && unlink_file (to) && !existence_error (errno))
            error (1, errno, "unable to remove %s", to);

        if ((fdout = creat (to, (int) sb.st_mode & 07777)) < 0)
            error (1, errno, "cannot create %s for copying", to);

        zstatus = inflateInit2 (&zstr, 47);
        if(zstatus != Z_OK)
            error(1, 0, "expansion error (INIT): (%d)%s", zstatus,zstr.msg);

        if (sb.st_size > 0)
        {
            for (;;)
            {
                n = read (fdin, buf, sizeof(buf));
                if (n == -1)
                {
#ifdef EINTR
                    if (errno == EINTR)
                        continue;
#endif
                    error (1, errno, "cannot read file %s for copying", fn_root(from));
                }
                else if (n == 0)
                    break;

                zstr.next_in = (Bytef*)buf;
                zstr.avail_in = n;
                while(zstr.avail_in)
                {
                    zstr.next_out = (Bytef*)zbuf;
                    zstr.avail_out = sizeof(zbuf);
                    zstatus = inflate (&zstr, 0);
                    if(zstatus != Z_OK && zstatus != Z_STREAM_END)
                        error(1,0, "expansion error (inflate): (%d)%s", zstatus,zstr.msg);

                    n = sizeof(zbuf)-zstr.avail_out;
                    if (n && write(fdout, zbuf, n) != n) {
                        error (1, errno, "cannot write file %s for copying", to);
                    }
                }
                if(zstatus == Z_STREAM_END)
                    break;
            }

#ifdef HAVE_FSYNC
            if (fsync (fdout))
                error (1, errno, "cannot fsync file %s after copying", fn_root(to));
#endif

        }

        zstr.next_out = (Bytef*)zbuf;
        zstr.avail_out = sizeof(zbuf);
        zstatus = inflate (&zstr, Z_FINISH);
        if(zstatus != Z_OK && zstatus != Z_STREAM_END)
            error(1,0, "expansion error (Z_FINISH): (%d)%s", zstatus,zstr.msg);
        n = sizeof(zbuf)-zstr.avail_out;
        if (n && write(fdout, zbuf, n) != n) {
            error (1, errno, "cannot write file %s for copying", fn_root(to));
        }

        zstr.next_in = (Bytef*)buf;
        zstr.avail_in = 0;
        zstr.next_out = (Bytef*)zbuf;
        zstr.avail_out = sizeof(zbuf);
        zstatus = inflateEnd(&zstr);
        if(zstatus != Z_OK)
            error(1,0, "expansion error: %s", zstr.msg);

        if (close (fdin) < 0)
            error (0, errno, "cannot close %s", fn_root(from));
        if (close (fdout) < 0)
            error (1, errno, "cannot close %s", fn_root(to));
    }

#ifdef UTIME_EXPECTS_WRITABLE
    if (!iswritable (to))
    {
        xchmod (to, 1);
        change_it_back = 1;
    }
#endif  /* UTIME_EXPECTS_WRITABLE  */
    /* now, set the times for the copied file to match those of the original */
    memset ((char *) &t, 0, sizeof (t));
    t.actime = sb.st_atime;
    t.modtime = sb.st_mtime;
    (void) utime (to, &t);
#ifdef UTIME_EXPECTS_WRITABLE
    if (change_it_back)
        xchmod (to, 0);
#endif  /*  UTIME_EXPECTS_WRITABLE  */
    return 0;
}
Esempio n. 17
0
/*
 * Copies "from" to "to".
 */
int copy_file (const char *from, const char *to, int force_overwrite, int must_exist)
{
    struct stat sb;
    struct utimbuf t;
    int fdin, fdout;
#ifdef UTIME_EXPECTS_WRITABLE
    int change_it_back = 0;
#endif

    TRACE(1,"copy(%s,%s)",PATCH_NULL(from),PATCH_NULL(to));
    if (noexec)
        return 0;

    /* If the file to be copied is a link or a device, then just create
       the new link or device appropriately. */
    if (islink (from))
    {
        char *source = xreadlink (from);
        symlink (source, to);
        xfree (source);
        return 0;
    }

    if (isdevice (from))
    {
#if defined(HAVE_MKNOD) && defined(HAVE_STRUCT_STAT_ST_RDEV)
        if (stat (from, &sb) < 0)
            error (1, errno, "cannot stat %s", fn_root(from));
        mknod (to, sb.st_mode, sb.st_rdev);
#else
        error (1, 0, "cannot copy device files on this system (%s)", fn_root(from));
#endif
    }
    else
    {
#ifdef MAC_HFS_STUFF
        /* Only use the mac specific copying routine in the client, since
           the server shouldn't have any need to handle resource forks
           (all the resource fork handling is done in the client -
            the server only handles flat files) */
        if ( !server_active ) {
            if (stat (from, &sb) < 0)
            {
                if(must_exist)
                    error (1, errno, "cannot stat %s", fn_root(from));
                else
                    return -1;
            }
            mac_copy_file(from, to, force_overwrite, must_exist);
        } else {
#endif
            /* Not a link or a device... probably a regular file. */
            if ((fdin = CVS_OPEN (from, O_RDONLY)) < 0)
            {
                if(must_exist)
                    error (1, errno, "cannot open %s for copying", fn_root(from));
                else
                    return -1;
            }
            if (fstat (fdin, &sb) < 0)
            {
                if(must_exist)
                    error (1, errno, "cannot fstat %s", fn_root(from));
                else
                {
                    close(fdin);
                    return -1;
                }
            }
            if (force_overwrite && unlink_file (to) && !existence_error (errno))
                error (1, errno, "unable to remove %s", to);

            if ((fdout = creat (to, (int) sb.st_mode & 07777)) < 0)
                error (1, errno, "cannot create %s for copying", fn_root(to));
            if (sb.st_size > 0)
            {
                char buf[BUFSIZ];
                int n;

                for (;;)
                {
                    n = read (fdin, buf, sizeof(buf));
                    if (n == -1)
                    {
#ifdef EINTR
                        if (errno == EINTR)
                            continue;
#endif
                        error (1, errno, "cannot read file %s for copying", fn_root(from));
                    }
                    else if (n == 0)
                        break;

                    if (write(fdout, buf, n) != n) {
                        error (1, errno, "cannot write file %s for copying", fn_root(to));
                    }
                }

#ifdef HAVE_FSYNC
                if (fsync (fdout))
                    error (1, errno, "cannot fsync file %s after copying", fn_root(to));
#endif
            }

            if (close (fdin) < 0)
                error (0, errno, "cannot close %s", fn_root(from));
            if (close (fdout) < 0)
                error (1, errno, "cannot close %s", fn_root(to));
#ifdef MAC_HFS_STUFF
        }
#endif
    }


#ifdef UTIME_EXPECTS_WRITABLE
    if (!iswritable (to))
    {
        xchmod (to, 1);
        change_it_back = 1;
    }
#endif  /* UTIME_EXPECTS_WRITABLE  */
    /* now, set the times for the copied file to match those of the original */
    memset ((char *) &t, 0, sizeof (t));
    t.actime = sb.st_atime;
    t.modtime = sb.st_mtime;
    (void) utime (to, &t);
#ifdef UTIME_EXPECTS_WRITABLE
    if (change_it_back)
        xchmod (to, 0);
#endif  /*  UTIME_EXPECTS_WRITABLE  */
    return 0;
}
Esempio n. 18
0
char *getmodes(File *file)
{
    char *unknownmodes = "???????????";
    char *modes = malloc((strlen(unknownmodes) + 1) * sizeof(*modes));
    if (!modes) {
        return strdup(unknownmodes);
    }
    struct stat *pstat = getstat(file);
    if (!pstat) {
        free(modes);
        return strdup(unknownmodes);
    }

    char *p = modes;
    if (islink(file))
        *p++ = 'l';
    else if (isdir(file))
        *p++ = 'd';
    else if (isblockdev(file))
        *p++ = 'b';
    else if (ischardev(file))
        *p++ = 'c';
    else if (isfifo(file))
        *p++ = 'p';
    else if (issock(file))
        *p++ = 's';
    else
        *p++ = '-';

    if (pstat->st_mode & S_IRUSR)
        *p++ = 'r';
    else
        *p++ = '-';

    if (pstat->st_mode & S_IWUSR)
        *p++ = 'w';
    else
        *p++ = '-';

    if (issetuid(file)) {
        if (pstat->st_mode & S_IXUSR)
            *p++ = 's';
        else
            *p++ = 'S';
    } else {
        if (pstat->st_mode & S_IXUSR)
            *p++ = 'x';
        else
            *p++ = '-';
    }

    if (pstat->st_mode & S_IRGRP)
        *p++ = 'r';
    else
        *p++ = '-';

    if (pstat->st_mode & S_IWGRP)
        *p++ = 'w';
    else
        *p++ = '-';

    if (issetgid(file)) {
        if (pstat->st_mode & S_IXGRP)
            *p++ = 's';
        else
            *p++ = 'S';
    } else {
        if (pstat->st_mode & S_IXGRP)
            *p++ = 'x';
        else
            *p++ = '-';
    }

    if (pstat->st_mode & S_IROTH)
        *p++ = 'r';
    else
        *p++ = '-';

    if (pstat->st_mode & S_IWOTH)
        *p++ = 'w';
    else
        *p++ = '-';

    if (issticky(file)) {
        if (pstat->st_mode & S_IXOTH)
            *p++ = 't';
        else
            *p++ = 'T';
    } else {
        if (pstat->st_mode & S_IXOTH)
            *p++ = 'x';
        else
            *p++ = '-';
    }

    /* POSIX says we should print a space if there are no extended ACLs,
       GNU ls prints nothing
       follow POSIX */
    if (!islink(file) && hasacls(file))
        *p++ = '+';
    else
        *p++ = ' ';

    *p++ = '\0';
    return modes;
}
Esempio n. 19
0
/*
 * Copies "from" to "to".
 */
void
copy_file (const char *from, const char *to)
{
    struct stat sb;
    struct utimbuf t;
    int fdin, fdout;
    ssize_t rsize;

    TRACE (TRACE_FUNCTION, "copy(%s,%s)", from, to);

    if (noexec)
	return;

    /* If the file to be copied is a link or a device, then just create
       the new link or device appropriately. */
    if ((rsize = islink (from)) > 0)
    {
	char *source = Xreadlink (from, rsize);
	symlink (source, to);
	free (source);
	return;
    }

    if (isdevice (from))
    {
#if defined(HAVE_MKNOD) && defined(HAVE_STRUCT_STAT_ST_RDEV)
	if (stat (from, &sb) < 0)
	    error (1, errno, "cannot stat %s", from);
	mknod (to, sb.st_mode, sb.st_rdev);
#else
	error (1, 0, "cannot copy device files on this system (%s)", from);
#endif
    }
    else
    {
	/* Not a link or a device... probably a regular file. */
	if ((fdin = open (from, O_RDONLY)) < 0)
	    error (1, errno, "cannot open %s for copying", from);
	if (fstat (fdin, &sb) < 0)
	    error (1, errno, "cannot fstat %s", from);
	if ((fdout = creat (to, (int) sb.st_mode & 07777)) < 0)
	    error (1, errno, "cannot create %s for copying", to);
	if (sb.st_size > 0)
	{
	    char buf[BUFSIZ];
	    int n;
	    
	    for (;;) 
	    {
		n = read (fdin, buf, sizeof(buf));
		if (n == -1)
		{
#ifdef EINTR
		    if (errno == EINTR)
			continue;
#endif
		    error (1, errno, "cannot read file %s for copying", from);
		}
		else if (n == 0) 
		    break;
		
		if (write(fdout, buf, n) != n) {
		    error (1, errno, "cannot write file %s for copying", to);
		}
	    }
	}

	if (close (fdin) < 0) 
	    error (0, errno, "cannot close %s", from);
	if (close (fdout) < 0)
	    error (1, errno, "cannot close %s", to);
    }

    /* preserve last access & modification times */
    memset ((char *) &t, 0, sizeof (t));
    t.actime = sb.st_atime;
    t.modtime = sb.st_mtime;
    (void) utime (to, &t);
}
Esempio n. 20
0
gboolean vdtree_press_cb(GtkWidget *widget, GdkEventButton *bevent, gpointer data)
{
	ViewDir *vd = data;
	GtkTreePath *tpath;
	GtkTreeViewColumn *column;
	GtkTreeIter iter;
	NodeData *nd = NULL;
	FileData *fd;

	if (gtk_tree_view_get_path_at_pos(GTK_TREE_VIEW(widget), bevent->x, bevent->y,
					  &tpath, &column, NULL, NULL))
		{
		GtkTreeModel *store;
		gint left_of_expander;

		store = gtk_tree_view_get_model(GTK_TREE_VIEW(widget));
		gtk_tree_model_get_iter(store, &iter, tpath);
		gtk_tree_model_get(store, &iter, DIR_COLUMN_POINTER, &nd, -1);
		gtk_tree_view_set_cursor(GTK_TREE_VIEW(widget), tpath, NULL, FALSE);

		if (vdtree_clicked_on_expander(GTK_TREE_VIEW(widget), tpath, column, bevent->x, bevent->y, &left_of_expander))
			{
			vd->click_fd = NULL;

			/* clicking this region should automatically reveal an expander, if necessary
			 * treeview bug: the expander will not expand until a button_motion_event highlights it.
			 */
			if (bevent->button == MOUSE_BUTTON_LEFT &&
			    !left_of_expander &&
			    !gtk_tree_view_row_expanded(GTK_TREE_VIEW(vd->view), tpath))
				{
				vdtree_populate_path_by_iter(vd, &iter, FALSE, vd->dir_fd);

				fd = (nd) ? nd->fd : NULL;
				if (fd && islink(fd->path))
					{
					vdtree_icon_set_by_iter(vd, &iter, vd->pf->link);
					}
				else
					{
					vdtree_icon_set_by_iter(vd, &iter, vd->pf->open);
					}
				}

			gtk_tree_path_free(tpath);
			return FALSE;
			}

		gtk_tree_path_free(tpath);
		}

	vd->click_fd = (nd) ? nd->fd : NULL;
	vd_color_set(vd, vd->click_fd, TRUE);

	if (bevent->button == MOUSE_BUTTON_RIGHT)
		{
		vd->popup = vd_pop_menu(vd, vd->click_fd);
		gtk_menu_popup(GTK_MENU(vd->popup), NULL, NULL, NULL, NULL,
			       bevent->button, bevent->time);
		}

	return (bevent->button != MOUSE_BUTTON_LEFT);
}
Esempio n. 21
0
/*
 * Finds all the subdirectories of the argument dir and adds them to
 * the specified list.  Sub-directories without a CVS administration
 * directory are optionally ignored.  If ENTRIES is not NULL, all
 * files on the list are ignored.  Returns 0 for success or 1 on
 * error, in which case errno is set to indicate the error.
 */
static int find_dirs (const char *dir, List *list, int checkadm, List *entries, const char *regex)
{
    Node *p;
    char *tmp = NULL;
    size_t tmp_size = 0;
    struct dirent *dp;
    DIR *dirp;
    int skip_emptydir = 0;

    /* First figure out whether we need to skip directories named
       Emptydir.  Except in the CVSNULLREPOS case, Emptydir is just
       a normal directory name.  */
    if (isabsolute (dir)
	&& fnncmp (dir, current_parsed_root->directory, strlen (current_parsed_root->directory)) == 0
	&& ISDIRSEP (dir[strlen (current_parsed_root->directory)])
	&& fncmp (dir + strlen (current_parsed_root->directory) + 1, CVSROOTADM) == 0)
	skip_emptydir = 1;

    /* set up to read the dir */
    if ((dirp = opendir (dir)) == NULL)
	return (1);

    /* read the dir, grabbing sub-dirs */
    errno = 0;
    while ((dp = readdir (dirp)) != NULL)
    {
	if (fncmp (dp->d_name, ".") == 0 ||
	    fncmp (dp->d_name, "..") == 0 ||
	    fncmp (dp->d_name, CVSATTIC) == 0 ||
	    fncmp (dp->d_name, CVSLCK) == 0 ||
	    fncmp (dp->d_name, CVSREP) == 0 ||
		fncmp (dp->d_name, CVSDUMMY) == 0)
	    goto do_it_again;

	/* findnode() is going to be significantly faster than stat()
	   because it involves no system calls.  That is why we bother
	   with the entries argument, and why we check this first.  */
	if (entries != NULL && findnode_fn (entries, dp->d_name) != NULL)
	    goto do_it_again;

	if (skip_emptydir
	    && fncmp (dp->d_name, CVSNULLREPOS) == 0)
	    goto do_it_again;

	    /* don't bother stating ,v files */
	    if (CVS_FNMATCH (RCSPAT, dp->d_name, CVS_CASEFOLD) == 0)
		goto do_it_again;

	    expand_string (&tmp,
			   &tmp_size,
			   strlen (dir) + strlen (dp->d_name) + 10);
	    sprintf (tmp, "%s/%s", dir, dp->d_name);
	    if (!isdir (tmp))
		goto do_it_again;

	/* check for administration directories (if needed) */
	if (checkadm)
	{
	    /* blow off symbolic links to dirs in local dir */
		/* Note that we only get here if we already set tmp
		   above.  */
		if (islink (tmp))
		    goto do_it_again;

	    /* check for new style */
	    expand_string (&tmp,
			   &tmp_size,
			   (strlen (dir) + strlen (dp->d_name)
			    + sizeof (CVSADM) + 10));
	    (void) sprintf (tmp, "%s/%s/%s", dir, dp->d_name, CVSADM);
	    if (!isdir (tmp))
		goto do_it_again;
	}

	/* If there's a regex, test against the name with '/' on the end to signify a directory */
	if(regex)
	{
		strcpy(tmp,dp->d_name);
		strcat(tmp,"/");
		if(!regex_filename_match(regex,tmp))
			goto do_it_again;
	}

	/* put it in the list */
	p = getnode ();
	p->type = DIRS;
	p->key = xstrdup (dp->d_name);
	if (addnode (list, p) != 0)
	    freenode (p);

    do_it_again:
	errno = 0;
    }
    if (errno != 0)
    {
	int save_errno = errno;
	(void) closedir (dirp);
	errno = save_errno;
	return 1;
    }
    (void) closedir (dirp);
    if (tmp != NULL)
	xfree (tmp);
    return (0);
}
Esempio n. 22
0
gboolean vdtree_populate_path_by_iter(ViewDir *vd, GtkTreeIter *iter, gboolean force, FileData *target_fd)
{
	GtkTreeModel *store;
	GList *list;
	GList *work;
	GList *old;
	time_t current_time;
	GtkTreeIter child;
	NodeData *nd;
	gboolean add_hidden = FALSE;
	gchar *link = NULL;

	store = gtk_tree_view_get_model(GTK_TREE_VIEW(vd->view));
	gtk_tree_model_get(store, iter, DIR_COLUMN_POINTER, &nd, -1);

	if (!nd) return FALSE;

	current_time = time(NULL);

	if (nd->expanded)
		{
		if (!nd->fd || !isdir(nd->fd->path))
			{
			if (vd->click_fd == nd->fd) vd->click_fd = NULL;
			if (vd->drop_fd == nd->fd) vd->drop_fd = NULL;
			gtk_tree_store_remove(GTK_TREE_STORE(store), iter);
			vdtree_node_free(nd);
			return FALSE;
			}
		if (!force && current_time - nd->last_update < 2)
			{
			DEBUG_1("Too frequent update of %s", nd->fd->path);
			return TRUE;
			}
		file_data_check_changed_files(nd->fd); /* make sure we have recent info */
		}

	/* when hidden files are not enabled, and the user enters a hidden path,
	 * allow the tree to display that path by specifically inserting the hidden entries
	 */
	if (!options->file_filter.show_hidden_files &&
	    target_fd &&
	    strncmp(nd->fd->path, target_fd->path, strlen(nd->fd->path)) == 0)
		{
		gint n;

		n = strlen(nd->fd->path);
		if (target_fd->path[n] == G_DIR_SEPARATOR && target_fd->path[n+1] == '.')
			add_hidden = TRUE;
		}

	if (nd->expanded && (!force && !add_hidden) && nd->fd->version == nd->version)
		return TRUE;

	vdtree_busy_push(vd);

	filelist_read(nd->fd, NULL, &list);

	if (add_hidden)
		{
		gint n;
		gchar *name8;

		n = strlen(nd->fd->path) + 1;

		while (target_fd->path[n] != '\0' && target_fd->path[n] != G_DIR_SEPARATOR) n++;
		name8 = g_strndup(target_fd->path, n);

		if (isdir(name8))
			{
			list = g_list_prepend(list, file_data_new_dir(name8));
			}

		g_free(name8);
		}

	old = NULL;
	if (gtk_tree_model_iter_children(store, &child, iter))
		{
		do	{
			NodeData *cnd;

			gtk_tree_model_get(store, &child, DIR_COLUMN_POINTER, &cnd, -1);
			old = g_list_prepend(old, cnd);
			} while (gtk_tree_model_iter_next(store, &child));
		}

	work = list;
	while (work)
		{
		FileData *fd;

		fd = work->data;
		work = work->next;

		if (strcmp(fd->name, ".") == 0 || strcmp(fd->name, "..") == 0)
			{
			file_data_unref(fd);
			}
		else
			{
			NodeData *cnd;

			cnd = vdtree_find_iter_by_fd(vd, iter, fd, &child);
			if (cnd)
				{
				if (cnd->expanded && cnd->version != fd->version)
					{
					vdtree_populate_path_by_iter(vd, &child, FALSE, target_fd);
					}

				gtk_tree_store_set(GTK_TREE_STORE(store), &child, DIR_COLUMN_NAME, fd->name, -1);

				if (islink(fd->path))
					{
					link = realpath(fd->path, NULL);
					}
				else
					{
					link = NULL;
					}

				gtk_tree_store_set(GTK_TREE_STORE(store), &child, DIR_COLUMN_LINK, link, -1);

				cnd->version = fd->version;
				old = g_list_remove(old, cnd);
				file_data_unref(fd);
				}
			else
				{
				vdtree_add_by_data(vd, fd, iter);
				}
			}
		}

	work = old;
	while (work)
		{
		NodeData *cnd = work->data;
		work = work->next;

		if (vd->click_fd == cnd->fd) vd->click_fd = NULL;
		if (vd->drop_fd == cnd->fd) vd->drop_fd = NULL;

		if (vdtree_find_iter_by_data(vd, iter, cnd, &child))
			{
			gtk_tree_store_remove(GTK_TREE_STORE(store), &child);
			vdtree_node_free(cnd);
			}
		}

	g_list_free(old);
	g_list_free(list);

	vdtree_busy_pop(vd);

	nd->expanded = TRUE;
	nd->last_update = current_time;

	g_free(link);

	return TRUE;
}
Esempio n. 23
0
static void vdtree_add_by_data(ViewDir *vd, FileData *fd, GtkTreeIter *parent)
{
	GtkTreeStore *store;
	GtkTreeIter child;
	NodeData *nd;
	GdkPixbuf *pixbuf;
	NodeData *end;
	GtkTreeIter empty;
	gchar *link = NULL;

	if (!fd) return;

	if (access_file(fd->path, R_OK | X_OK))
		{
		if (islink(fd->path))
			{
			pixbuf = vd->pf->link;
			}
		else
			{
			pixbuf = vd->pf->close;
			}
		}
	else
		{
		pixbuf = vd->pf->deny;
		}

	nd = g_new0(NodeData, 1);
	nd->fd = fd;
	nd->version = fd->version;
	nd->expanded = FALSE;
	nd->last_update = time(NULL);

	if (islink(fd->path))
		{
		link = realpath(fd->path, NULL);
		}
	else
		{
		link = NULL;
		}

	store = GTK_TREE_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(vd->view)));
	gtk_tree_store_append(store, &child, parent);
	gtk_tree_store_set(store, &child, DIR_COLUMN_POINTER, nd,
					 DIR_COLUMN_ICON, pixbuf,
					 DIR_COLUMN_NAME, nd->fd->name,
					 DIR_COLUMN_LINK, link,
					 DIR_COLUMN_COLOR, FALSE, -1);

	/* all nodes are created with an "empty" node, so that the expander is shown
	 * this is removed when the child is populated */
	end = g_new0(NodeData, 1);
	end->fd = NULL;
	end->expanded = TRUE;

	gtk_tree_store_append(store, &empty, &child);
	gtk_tree_store_set(store, &empty, DIR_COLUMN_POINTER, end,
					  DIR_COLUMN_NAME, "empty", -1);

	if (parent)
		{
		NodeData *pnd;
		GtkTreePath *tpath;

		gtk_tree_model_get(GTK_TREE_MODEL(store), parent, DIR_COLUMN_POINTER, &pnd, -1);
		tpath = gtk_tree_model_get_path(GTK_TREE_MODEL(store), parent);
		if (options->tree_descend_subdirs &&
		    gtk_tree_view_row_expanded(GTK_TREE_VIEW(vd->view), tpath) &&
		    !nd->expanded)
			{
			vdtree_populate_path_by_iter(vd, &child, FALSE, vd->dir_fd);
			}
		gtk_tree_path_free(tpath);
		}

	g_free(link);
}
Esempio n. 24
0
void main(int argc,String *argv) {
  
  String batname=Sconc(JPATH(),"/tmp/forall.bat");

  ArgParser a=ArgParser(argc,argv);
//    a.comment("Syntax: forall <files> do <command>\n");
//    a.comment("    or: forall in <filename> do <command>\n");
    a.comment("  <command> may use %f as the filename,");
    a.comment("    %s as the filename stripped of extensions,");
    a.comment("    %e as the filename's extension,");
    a.comment("    %l as %f in lower case,");
    a.comment("    %L as %w in lower case,");
    a.comment("    %w as the whole path of the filename,");
    a.comment("    %n as the number of the file being processed,");
    a.comment("    %a as & , %p as > , %q as \" ,");
    a.comment("    and : to seperate commands.");
    #ifdef DOS
      a.comment("    For DOS, use $ instead of %");
    #endif
  bool dirsonly=a.argexists("-dirsonly","execute command on directories only");
  bool filesonly=a.argexists("-filesonly","execute command on non-directories only");
  bool linkeddirsok=a.argexists("-followdirs","follow sym linked directories");
  bool linkedfilesok=!a.argexists("-nofollowfiles","don't follow sym linked files");
  bool showprogress=a.argexists("-showprog","show progress");
  bool shell=a.argexists("-shell","run commands through a shell file");
  a.comment("    A forall command in shell mode is not the same in non-shell mode");
  a.comment("    since in the shell program the state will persist between each file.");
  bool ccomments =!a.argexists("-//","[in]: ignore // commenting");
  bool shcomments=!a.argexists("-#"," [in]: ignore # commenting");
  quiet=a.argexists("-stealth","don't print stuff");
  int padzeros=a.intafter("-padzeros","pad %n with this many 0s on left",3);
  String padzeroformat=Sformat("%s0%ii","%",padzeros);
  bool checkforfilename=false;
  if (argc<3 || a.helpon) {
    a.com="forall <files> do <command>   OR\nforall in <filename> do <command>";
    a.helpon=true;
    a.done();
    exit(0);
  }

  // Read files until do
  if (showprogress)
    printf("Files: ");
  List<String> fs;
  if (!Seq(a.arg(1),"in")) { // Files provided as arguments
    String s="";
    while (!Seq(s,"do") && a.argsleft()) {
      s=a.getarg(1);
      if (!Seq(s,"do")) {
        if (showprogress)
          printf("%s ",s);
        boolean okay=true;
//        if (checkforfilename)
//          fs.add(getfiles(s));
//        else
/*        if (!fileexists(s)) {
          if (!quiet)
            printf("Didn't find file %s\n",s);
          okay=false;
        }*/
        if (isdir(s)) {
          if (filesonly)
            okay=false;
          if (islink(s) && !linkeddirsok)
            okay=false;
        } else { // not dir => file
          if (dirsonly)
            okay=false;
          if (islink(s) && !linkedfilesok)
            okay=false;
        }
        if ( (dirsonly || filesonly) &&
             !fileexists(s) )
          okay=false;
        if ((Sinstr(s,"*")>0) || (Sinstr(s,"?")>0)) { // Unresolved wildcard
          okay=false;
          if (!quiet)
            printf("forall: Did not find any \"%s\"\n",s);
        }
        if (Slen(s)==0)
          okay=false;
        if (okay)
          fs.add(s);
      }
    }
  } else { // Points to file containing list of files for forall
    String tmp=a.getarg(1);
    String fname=a.getarg(1);
    tmp=a.getarg(1);
    if (!Seq(tmp,"do"))
      error("Expected do in forall in <fname> do ...");
    fs.add(readlinesfromfile(fname));
    for (int i=1;i<=fs.len;i++) {
      String s=fs.num(i);
      if ( Slen(s)==0
        || (dirsonly && !isdir(s))
        || (filesonly && isdir(s))
        || (ccomments && Sstarts(s,"//"))
        || (shcomments && Sstarts(s,"#")) ) {
        fs.removenumkeeporder(i);
        i--;
      }
    }
    if (showprogress)
      printf("%s ",fs.num(fs.len));
  }
  if (showprogress)
    printf("\n");

  // Read command after do
  if (showprogress)
    printf("Command: ");
  a.com=Sconc(a.com,"do <command> ");
  List<String> ls;
  while (a.argsleft()) {
    ls.add(Ssplitaround(a.getarg(1)," "));
    if (showprogress)
      printf("\"%s\" ",ls.num(ls.len));
  }
  if (showprogress)
    printf("\n");
  if (ls.len==0)
    a.error("You must provide <command>");
  a.done();
  
  FILE *progress=NULL;
  progress=fopen("forall.progress","w");
  List<String> coms;
  for (int i=1;i<=fs.len;i++) {
    String whole=fs.num(i);
    if (Slen(whole)>0) {
      String fname;
      int n=max(Sinstrlast(whole,"/"),Sinstrlast(whole,"\\"));
      if (n==0)
        fname=whole;
      else
        fname=Sfrom(whole,n+1);
      String strlow=Stolower(fname);
      String wholelow=Stolower(whole);
      /* Remove all '.'s
      int k;
      while ((k=Sinstr(str,"."))>0) {
        str=Sleft(str,k-1);
      } */
      int k=Sinstrlast(fname,".");
      String str=( k<=0 ? fname : Sleft(fname,k-1) );
      String ext=( k<=0 ? Snew("") : Sfrom(fname,k+1) );
      // List<String> coms;
      if (!shell)
        coms.clear();
      String com="";
      for (int j=1;j<=ls.len;j++) {
        String arg=ls.num(j);
  //      if (showprogress)
  //        printf("%s -> ",arg);
        #ifdef DOS
        arg=Sreplaceall(arg,"$n",Sformat(padzeroformat,i));
        arg=Sreplaceall(arg,"$a","&");
        arg=Sreplaceall(arg,"$f",fname);
        arg=Sreplaceall(arg,"$w",whole);
        arg=Sreplaceall(arg,"$s",str);
        arg=Sreplaceall(arg,"$e",ext);
        arg=Sreplaceall(arg,"$l",strlow);
        arg=Sreplaceall(arg,"$L",wholelow);
        arg=Sreplaceall(arg,"$p",">");
        arg=Sreplaceall(arg,"$q","\"");
        #else
        arg=Sreplaceall(arg,"\%n",Sformat(padzeroformat,i));
        arg=Sreplaceall(arg,"\%a","&");
        arg=Sreplaceall(arg,"\%f",fname);
        arg=Sreplaceall(arg,"\%w",whole);
        arg=Sreplaceall(arg,"\%s",str);
        arg=Sreplaceall(arg,"\%e",ext);
        arg=Sreplaceall(arg,"\%l",strlow);
        arg=Sreplaceall(arg,"\%L",wholelow);
        arg=Sreplaceall(arg,"\%p",">");
        arg=Sreplaceall(arg,"\%q","\"");
        #endif
  //      if (showprogress)
  //        printf("%s -> ",arg);
        if (Seq(arg,":")) {
          com=Srls(com);
          if (!quiet) {
            // printf("# (%03i/%i) %s\n",i,fs.len,com);
            String output=Sformat("# (%03i/%i) %s",i,fs.len,com);
            if (shell) // Print it later when the shell is being executed
              coms.add(Sconc("echo \"",Stoechoformat(output),"\""));
            else
              printf("%s\n",output);
          }
          if (shell)
            coms.add(com);
          else
            system(com);
          com="";
        } else
          com=Sconc(com," ",arg);
  /*      if (showprogress) {
          printf("%s\n>",com);
          for (int k=1;k<=ls.len;k++)
            printf("%s ",ls.num(k));
          printf("\n");
        }*/
      }
      com=Srls(com);
          if (!quiet) {
            String output=Sformat("# (%03i/%i) %s",i,fs.len,com);
            if (shell) // Print it later when the shell is being executed
              coms.add(Sconc("echo \"",Stoechoformat(output),"\""));
            else
              printf("%s\n",output);
          }
      if (progress!=NULL)
        fprintf(progress,"-%03i/%i- %s\n",i,fs.len,com);
      if (shell)
        coms.add(com);
      else
        system(com);
    }
  }
Esempio n. 25
0
static void
tree_expand_node (DirTree * dt, GtkCTreeNode * node, gboolean expand)
{
    GtkCTreeNode *child;
    DirTreeNode *parent_node;
    DirTreeNode *child_node;
    DIR    *dir;
    struct stat stat_buff;
    struct dirent *entry;
    gboolean has_subdirs, has_link, has_access;
    char   *old_path;
    char   *subdir = "?";
    char   *file_name;
    GtkWidget *top = gtk_widget_get_toplevel (GTK_WIDGET (dt));
    old_path = g_get_current_dir ();

    if (!old_path)
	return;

    parent_node = gtk_ctree_node_get_row_data (GTK_CTREE (dt), node);

    if (chdir (parent_node->path))
    {
	g_free (old_path);
	return;
    }

    dir = opendir (".");

    if (!dir)
    {
	chdir (old_path);
	g_free (old_path);
	return;
    }

    dirtree_set_cursor (top, GDK_WATCH);

    gtk_clist_freeze (GTK_CLIST (dt));

    tree_collapse (GTK_CTREE (dt), node);

    child = NULL;

    while ((entry = readdir (dir)))
    {
	if (!stat (entry->d_name, &stat_buff) && S_ISDIR (stat_buff.st_mode)
	    && tree_is_dotfile (entry->d_name, dt->show_dotfile))
	{
	    child_node = g_malloc0 (sizeof (DirTreeNode));

	    child_node->path =
		g_strconcat (parent_node->path, "/", entry->d_name, NULL);

	    has_link = islink (entry->d_name);
	    has_access = access (entry->d_name, X_OK);

	    file_name = entry->d_name;

	    if (has_access)
	    {
		child = gtk_ctree_insert_node (GTK_CTREE (dt),
					       node, child,
					       &file_name,
					       CTREE_SPACING,
					       lckfolder_pixmap,
					       lckfolder_mask, NULL,
					       NULL, 1, 0);
		has_subdirs = FALSE;
	    }
	    else if (!strcmp (entry->d_name, "."))
	    {
		child = gtk_ctree_insert_node (GTK_CTREE (dt),
					       node, child,
					       &file_name,
					       CTREE_SPACING,
					       gofolder_pixmap,
					       gofolder_mask, NULL,
					       NULL, 1, 0);

		has_subdirs = FALSE;
	    }
	    else if (!strcmp (entry->d_name, ".."))
	    {
		child = gtk_ctree_insert_node (GTK_CTREE (dt),
					       node, child,
					       &file_name,
					       CTREE_SPACING,
					       upfolder_pixmap,
					       upfolder_mask, NULL,
					       NULL, 1, 0);

		has_subdirs = FALSE;
	    }
	    else
	    {
		if (dt->check_dir)
		{
		    if (dt->check_hlinks)
		    {
			if (stat_buff.st_nlink == 2 && dt->show_dotfile)
			    has_subdirs = TRUE;
			else if (stat_buff.st_nlink > 2)
			    has_subdirs = TRUE;
			else if (stat_buff.st_nlink == 1)
			    has_subdirs =
				tree_is_subdirs (entry->d_name,
						 dt->show_dotfile);
			else
			    has_subdirs = FALSE;
		    }
		    else
			has_subdirs =
			    tree_is_subdirs (entry->d_name, dt->show_dotfile);

		}
		else
		    has_subdirs = TRUE;

		if (access (entry->d_name, X_OK) != 0)
		{
		    has_subdirs = FALSE;
		}

		if (has_link)
		    child = gtk_ctree_insert_node (GTK_CTREE (dt),
						   node, child,
						   &file_name,
						   CTREE_SPACING,
						   lfolder_pixmap,
						   lfolder_mask,
						   lofolder_pixmap,
						   lofolder_mask,
						   !has_subdirs, 0);
		else
		    child = gtk_ctree_insert_node (GTK_CTREE (dt),
						   node, child,
						   &file_name,
						   CTREE_SPACING,
						   folder_pixmap,
						   folder_mask,
						   ofolder_pixmap,
						   ofolder_mask,
						   !has_subdirs, 0);
	    }

	    if (child)
	    {
		gtk_ctree_node_set_row_data_full (GTK_CTREE (dt), child,
						  child_node,
						  dirtree_destroy_tree);

		if (has_subdirs)
		    gtk_ctree_insert_node (GTK_CTREE (dt),
					   child, NULL,
					   &subdir,
					   CTREE_SPACING,
					   NULL, NULL, NULL, NULL, 0, 0);
	    }
	}

	if (dt->check_events)
	    while (gtk_events_pending ())
		gtk_main_iteration ();
    }

    closedir (dir);

    chdir (old_path);
    g_free (old_path);

    gtk_ctree_sort_node (GTK_CTREE (dt), node);

    if (expand == TRUE)
	gtk_ctree_expand (GTK_CTREE (dt), node);

    gtk_clist_thaw (GTK_CLIST (dt));

    dirtree_set_cursor (top, -1);
}