pax_global_header00006660000000000000000000000064123013703760014514gustar00rootroot0000000000000052 comment=55279f0366c32e4295c9f114cbee5ac7776e4d53 ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/000077500000000000000000000000001230137037600175125ustar00rootroot00000000000000ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/.gitignore000066400000000000000000000000071230137037600214770ustar00rootroot00000000000000 ondir ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/.todo000066400000000000000000000015201230137037600204560ustar00rootroot00000000000000 OnDir Rewrite in C to make it more portable? Support for tcsh Obtain enter/leave list from a user-specific config file? (~/.ondir?) Would alleviate security problems. There are two problems with the RC file. One is that if there are unmatched braces, the lexer will die. The other is if there are strings which contain newlines inside the scripts they will be changed to ;'s. ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/AUTHORS000066400000000000000000000000371230137037600205620ustar00rootroot00000000000000Alec Thomas ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/COPYING000066400000000000000000000431101230137037600205440ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/ChangeLog000066400000000000000000000071411230137037600212670ustar00rootroot000000000000000.2.2 * Added ~ expansion in ~/.ondirrc paths (only works if ~ is first character) * Added envar expansion in the definition and bodies of enter/leave sections. eg. enter $HOME/projects/.* echo "You have entered ${ONDIRWD}" * Added regular expression sub-pattern capturing. This lets you do things like: {{{ enter $HOME/cvs/([^/]+)/? echo "You have entered the CVS directory for $1" }}} $0 is equivalent to $ONDIRWD. Thanks to Wolfram Schlich for this idea. Nice. 0.2.1 * Fixed stupid compile problem when .onenter/.onleave support is enabled. Thanks to Steve Huff for picking this up. * Added a patch from Arvind SV which adds regex matching support for paths. Nice. eg. enter /usr/src/linux(-2.4.21(-xfs)?)? * Arvind also added $ONDIRWD support from the pre-0.2.x versions back in. Quite a handy thing to have, thanks Arvind. 0.2.0 * Rewritten in C. This makes it smaller and faster and no longer takes half an hour to compile. * Configuration file format has changed completely. Read the README or man page for more information. * No longer using autoconf/automake as it's overkill for 400 lines of source. 0.1.6 * Fixed some errors in the man page, picked up thanks to Wolfram Schlich. * Fixed some potential quoting problems in the man page and migrate.sh. 0.1.5 * Commented out some extraneous functions (drand) which were not being used but caused compile problems on OSX. * Fixed some other compilation issues on OSX. Thanks to Ben Hines for both of these OSX fixes. * Fixed some fairly major problems in the man page, referring to todorc rather than ondirrc. Thanks again to Ben Hines for picking this up. * Re-added .onenter/.onleave support, but optionally (use -o to enable this behaviour). * You can now pass the current working directory on the command line as the second option. This fixes problems with traversing paths containing symlinks. Thanks to Ralf Engelschall for pointing this out. * Cleaned up the code a bit. 0.1.4 * Applied a patch sent in by Jason Kissinger to fix some cases where ; was not being added to the end of shell lines, causing TCSH to barf. * The rc file lexer no longer uses regular expressions, but hard-coded lexical element recognisers. It is an order of magnitude faster. * OnDir will no longer execute .onenter or .onleave scripts. This was a security disaster waiting to happen. There is a script included in the distribution called migrate.sh which will migrate any existing .onenter/.onleave scripts into your ~/.ondirrc. It is used by passing the paths you wish to migrate as arguments. 0.1.3 * Fixed Makefile.am in ./src so all the source files are packaged - duh. * Changed static reference to ~athomas/.ondirrc to the generic case of $HOME/.ondirrc. Another stupid one. * Fixed broken TCSH handling. Thanks to Daniel Macks for hunting this down as well as the previous bug. 0.1.2 * Now check for a .onexit as well. * Unset ONDIRWD variable after scripts have executed. * Added a config file /etc/ondirrc or ~/.ondirrc that contains directories and enter/exit scripts. This is the most secure way of having scripts execute and is preferred over .onenter and .onleave. See man page for further information. Thanks to Darren Chamberlain for this idea. 0.1.1 * Added a patch sent in by Mira Tempír to check for group/other write permissions on the scripts and refuse to run them if they are set. Subsequently changed the name of the function to make more sense. * Added -V to display version. 0.1.0 * Released. ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/INSTALL000066400000000000000000000007231230137037600205450ustar00rootroot00000000000000The default is to install the binary and man page into /usr and to look for the global config in /etc. If you wish to install entirely into /usr/local, do the following: make PREFIX=/usr/local CONF=/usr/local/etc/ondirrc install To install to a "package root" do this: make DESTDIR=/tmp/ondir.pkg install Once you have installed OnDir, add either scripts.sh or scripts.tcsh to your startup. This will execute ondir whenever you change directories at the shell. ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/Makefile000066400000000000000000000034471230137037600211620ustar00rootroot00000000000000# Change these as you see fit PREFIX=/usr CONF=/etc/ondirrc SOURCES=conf.c ondir.c HEADERS=conf.h ondir.h OBJS=conf.o ondir.o TARGET=ondir VERSION=0.2.3 DESTDIR= # Add -DUSE_ONENTERLEAVE to CFLAGS to enable support for .onenter/.onleave # scripts. # **WARNING** This is not recommended at all. CC=cc CFLAGS=-O3 -DVERSION=\"$(VERSION)\" -DGLOBAL_CONF=\"$(CONF)\" -DUSE_ONENTERLEAVE CFLAGS=-Wall -c -g -DVERSION=\"$(VERSION)\" -DGLOBAL_CONF=\"$(CONF)\" LD=cc LDFLAGS= LDFLAGS=-g $(TARGET): $(OBJS) $(LD) $(OBJS) $(LDFLAGS) -o $@ @echo @echo "OnDir is built." @echo @echo "Type 'make DESTDIR= install' to install." @echo clean: rm -f $(OBJS) $(TARGET) install: $(TARGET) install -m 755 -d $(DESTDIR)$(PREFIX)/share/man/man1 install -m 644 ondir.1 $(DESTDIR)$(PREFIX)/share/man/man1 install -m 755 -d $(DESTDIR)$(PREFIX)/bin install -m 755 ondir $(DESTDIR)$(PREFIX)/bin package: slackware rpm chown athomas:athomas * chmod og-rwx * chmod a+r ondir-$(VERSION)* slackware: $(TARGET) # Make SlackWare package rm -rf /tmp/ondir.pkg && \ make DESTDIR=/tmp/ondir.pkg PREFIX=/usr CONF=/etc/ondirrc install && \ cd /tmp/ondir.pkg && \ makepkg -l y -c y ${PWD}/ondir-$(VERSION)-i386-1.tgz && \ rm -rf /tmp/ondir.pkg rpm: dist $(TARGET) cp ondir-$(VERSION).tar.gz /usr/src/rpm/SOURCES rpm -ba ondir.spec cp /usr/src/rpm/SRPMS/ondir-$(VERSION)-1.src.rpm ${PWD} cp /usr/src/rpm/RPMS/i386/ondir-$(VERSION)-1.i386.rpm ${PWD} dist: clean rm -f ondir-$(VERSION)* && \ cd .. && \ mv ondir ondir-$(VERSION) && \ tar -czv --exclude '.git*' --exclude 'old/*' --exclude '.*.swp' -f ondir-$(VERSION).tar.gz ondir-$(VERSION) && \ mv ondir-$(VERSION) ondir && \ mv ondir-$(VERSION).tar.gz ondir && \ chmod 644 ondir/ondir-$(VERSION).tar.gz dep: @makedepend $(CXXFLAGS) $(SOURCES) 2> /dev/null ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/README.rst000066400000000000000000000037041230137037600212050ustar00rootroot00000000000000OnDir ===== Introduction ------------ ondir is a small program to automate tasks specific to certain directories. It works by executing scripts in directories when you enter and leave them. Scripts in the doc subdirectory show how to automate this when using either BASH or TCSH. Getting Started --------------- 1. Add scripts.sh or scripts.tcsh to your startup scripts for BASH or TCSH, respectively. 2. Restart your shell. 3. Add an entry to your ~/.ondirrc such as those described below. 4. Change into the corresponding path. 5. Check for success. Details ------- An example of ondirs usefulness is when editing web pages. I have a umask of 077 by default, but when creating web pages in ~/public_html the web content has to be readable by the user the web server runs as. By adding a path section for this directory to my ~/.ondirrc, and corresponding enter and leave sub-sections, any scripts in the enter/leave sub-sections are executed when I enter and leave the directory, respectively. Here is how the entry in my ~/.ondirrc would look:: enter /home/athomas/public_html umask 022 leave /home/athomas/public_html umask 077 And that's all it does. Simple, but effective. ondir takes one parameter, the directory you are leaving. Note that these scripts will be executed when you pass THROUGH the directory as well. Using the preceding example, typing "cd ~/public_html/mywebpage" will execute the 'enter' in ~/public_html. The reverse is also true: when leaving a path, all 'leave' scripts in the intermediate directories are executed. A more useful example --------------------- Ondir is particularly useful with `virtualenv `_. The following config will automatically activate virtualenv's when you change into a directory and deactivate when you move out:: enter ~/Projects/([^/]+) if [ -r .venv ]; then . ./.venv/bin/activate fi leave ~/Projects/([^/]+) deactivate > /dev/null 2>&1 ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/TODO000066400000000000000000000000001230137037600201700ustar00rootroot00000000000000ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/conf.c000066400000000000000000000113341230137037600206050ustar00rootroot00000000000000#include #include #include #include #include #include "conf.h" static int count_ch(const char *str, int ch) { int count = 0; for (; str && *str; ++str) if (*str == ch) ++count; return count; } struct odpath_t *load_conf(const char *file, struct odpath_t *root) { char *buffer = malloc(2048), *section = malloc(16384); struct odpath_t *path = root, *current = NULL; FILE *fp; int line = 0, sec_size = 0; if (path) while (path->next) path = path->next; if (!(fp = fopen(file, "r"))) { free(buffer); free(section); return root; } while (fgets(buffer, 2048, fp)) { int line_size = strlen(buffer); ++line; /* empty lines and comments are ignored */ if (!strchr("#\n\r", buffer[0]) && line_size) { /* continuation... */ if (isspace(buffer[0])) { char *sol = buffer; if (!current) { error("%s:%i: data outside section", file, line); continue; } if (sec_size + line_size >= MAX_SECTION_SIZE) fatal("section is greater than MAX_SECTION_SIZE (%i)", MAX_SECTION_SIZE); /* strip leading spaces */ while (isspace(*sol)) ++sol; strcat(section, sol); } else { const char *home = getenv("HOME"); char *tok; char **paths; int npaths, pathi; /* new section... */ if (current) { current->content = strdup(section); if (path) { path->next = current; path = current; } else { path = current; if (!root) root = path; } } if (!(current = calloc(1, sizeof(struct odpath_t)))) fatal("malloc failed"); memset(section, 0, MAX_SECTION_SIZE); /* read stuff */ tok = strtok(buffer, " \t"); if (!tok) fatal("%s:%i: unexpected end of line", file, line); if (!strcmp(tok, "final")) { current->final = 1; tok = strtok(NULL, " \t"); } if (strcmp(tok, "enter") && strcmp(tok, "leave")) fatal("%s:%i: line should start with final, enter or leave", file, line); if (!strcmp(tok, "enter")) current->type = PT_ENTER; else if (!strcmp(tok, "leave")) current->type = PT_LEAVE; /* count :'s */ tok = strtok(NULL, "\n"); npaths = count_ch(tok, ':') + 1; paths = calloc(npaths, sizeof(char*)); for (pathi = 0, tok = strtok(tok, ":"); pathi < npaths; ++pathi, tok = strtok(NULL, ":")) { if (home && tok[0] == '~') { char tmppath[strlen(tok) + strlen(home) + 1]; strcpy(tmppath, home); strcat(tmppath, tok + 1); paths[pathi] = expand_envars(tmppath); } else paths[pathi] = expand_envars(tok); } current->paths = (const char**)paths; current->npaths = npaths; } } } if (current) { current->content = strdup(section); if (path) { path->next = current; path = current; } else { path = current; if (!root) root = path; } } fclose(fp); free(section); free(buffer); return root; } void fatal(const char *fmt, ...) { va_list args; fprintf(stderr, "fatal: "); va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); exit(1); } void error(const char *fmt, ...) { va_list args; fprintf(stderr, "error: "); va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); } void warning(const char *fmt, ...) { va_list args; printf("warning: "); va_start(args, fmt); vprintf(fmt, args); va_end(args); } void info(const char *fmt, ...) { va_list args; printf("ondir: "); va_start(args, fmt); vprintf(fmt, args); va_end(args); } /* Expand internal ONDIR environment variables */ char *expand_envars(const char *in) { int inlen = strlen(in), outmax = inlen * 2, outlen = 0; char *out = calloc(1, outmax); while (*in) { const char *mark = in; if (*in == '$') { int bracketed = 0, varlen = 0; const char *varstart; ++in; if (*in == '{') { ++in; bracketed = 1; } varstart = in; while (in[varlen] && (isalnum(in[varlen]) || in[varlen] == '_')) ++varlen; if (bracketed && in[varlen] != '}') in = mark; else { char var[varlen + 1]; const char *val; strncpy(var, varstart, varlen); var[varlen] = 0; if (strcmp(var, "ONDIRWD") && (var[0] < '0' || var[0] > '9')) { in = mark; } else { val = getenv(var); if (val) { int vallen = strlen(val); if (outlen + vallen >= outmax) { outmax = outmax * 2 + vallen; out = realloc(out, outmax); } strcat(out, val); outlen += vallen; in = mark + varlen + bracketed * 2 + 1; continue; } else { in = mark; out[outlen] = 0; } } } } /* Add another character */ if (outlen + 1 >= outmax) { outmax *= 2; out = realloc(out, outmax); } out[outlen++] = *in++; out[outlen] = 0; } out[outlen] = 0; return out; } ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/conf.h000066400000000000000000000014441230137037600206130ustar00rootroot00000000000000#ifndef CONF_H__ #define CONF_H__ /* Where the global config resides. */ #ifndef GLOBAL_CONF #define GLOBAL_CONF "/etc/ondirrc" #endif /* If your code blocks exceed this, something weird is going on. */ #define MAX_SECTION_SIZE 16384 /* Use .onenter or .onleave? */ /* #define USE_ONENTERLEAVE */ typedef enum { PT_ENTER, PT_LEAVE, } pathtype_t; struct odpath_t { const char **paths, *content; int npaths, final; pathtype_t type; struct odpath_t *next; }; /* load ondir configuration file */ struct odpath_t *load_conf(const char *file, struct odpath_t *root); /* Expand all environment variables in 'in' */ char *expand_envars(const char *in); void fatal(const char *fmt, ...); void error(const char *fmt, ...); void warning(const char *fmt, ...); void info(const char *fmt, ...); #endif ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/ondir.1000066400000000000000000000104301230137037600207050ustar00rootroot00000000000000.\" ondir is licensed under the GPL, version 2. A copy of the GPL should have been distributed with the source in the file COPYING .TH "ondir" "1" "0.2.3" "Alec Thomas" "Shell utility" .SH "NAME" .LP ondir \- automatically execute scripts when traversing directories at the command line .SH "SYNPOSIS" .LP \fBondir []\fP .LP .SH "DESCRIPTION" .LP \fBNOTE: The 0.2.x series has been completely rewritten in C. In addition, the configuration file format is substantially different. .LP \fBondir\fP is a program that executes a script when entering or leaving a directory. It also executes all scripts in the intermediate directories between the two. .LP For example, when changing from /opt/music to /home, leave scripts for /opt/music and /opt are executed, then the enter script for /home is executed. .LP The scripts are defined in either the system\-wide rc file (/etc/ondirrc) or per user rc files (~/.ondirrc). .LP The way \fBondir\fR works is by using auxiliary scripts that override shell builtins (cd, pushd and popd in BASH) to execute \fBondir\fR whenever a user changes directory. These scripts are included in the section SCRIPTS, below. .LP The scripts are available in the source tarball and are called \fBscripts.sh\fR, \fBscripts.tcsh\fR for Bourne shell variants and TCSH, respectively. .SH "OPTIONS" .TP \fB\fR The last directory you were in, after having changed to the new directory. .TP \fB[]\fR The current directory. This is optional, but can be useful when traversing symbolically linked paths, as it will use the logical path rather than the physical path. If left out, ondir uses getcwd(). .LP .SH "CONFIGURATION" .LP The configuration files /etc/ondirrc and ~/.ondirrc are in the form: .LP # Comment .br [final] enter \fB[:[:...]]\fR .br \fB\fR .br [final] leave \fB[:[:...]]\fR .br \fB\fR .LP Any line with leading whitespace is assumed to belong to the last valid enter or leave section. .LP \fBfinal\fB indicates that the section will be the last one executed for the matching directory. Directories further down the hierarchy will still be matched. .LP \fB\fR is the path to match. Regular expression support has been included since version 0.2.1 thanks to Arvind (?). A path must match completely to be considered a match. Because : is the path delimiter, it can not be used in any regular expressions. .LP Arvind also re-added (from version 0.1.x) support for $ONDIRWD expansion. This environment variable will contain the directory currently being traversed. .LP A perfect example of the usefulness of this program is a users public_html directory. .LP I personally set my default umask to 077, but when editing in my public_html directory I want my umask to be 022. To do this automatically, I would have add the following to my ~/.ondirrc .TP \fB~/.ondirrc\fR enter /home/athomas/public_html .br umask 022 .br leave /home/athomas/public_html .br umask 077 .LP Another good example is if you have a "bin" directory in a project, but don't want to add it permanently to your PATH. The following ondir scripts take care of that: .TP \fB~/.ondirrc\fR enter /home/athomas/projects/myproject .br PATH=$PATH:$CWD/bin .br leave /home/athomas/projects/myproject .br PATH=`echo $PATH | sed \-e "s,:$CWD/bin,,g"` .SH "SCRIPTS" .LP The BASH script you should add to your profile is: .LP cd() .br { .br builtin cd "$@" && eval "`ondir \\"$OLDPWD\\" \\"$PWD\\"`" .br } .br .br pushd() .br { .br builtin pushd "$@" && eval "`ondir \\"$OLDPWD\\" \\"$PWD\\"`" .br } .br .br popd() .br { .br builtin popd "$@" && eval "`ondir \\"$OLDPWD\\" \\"$PWD\\"`" .br } .br .br eval "`ondir /`" .br .LP The TCSH script you should add to your profile is: .LP alias cwdcmd eval \`ondir \-t \$owd \$cwd\` .br .br # Run ondir on login .br eval `ondir \-t /` .br .SH "AUTHORS" .LP Alec Thomas \fI\fR .SH "SEE ALSO" .LP devtodo(1) \fI\fR .SH "NOTES" .LP \fBondir\fR also has the ability to execute scripts in the directories being traversed. These scripts are named \fB.onenter\fR and \fB.onleave\fR. This ability is disabled by default, but can be enabled by editing conf.h and uncommenting: .LP #define USE_ONENTERLEAVE ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/ondir.c000066400000000000000000000164641230137037600210040ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include "conf.h" /* Declarations */ struct odpath_t *root; char *substitute(const char *in, const char *var, const char *val); int add_envar(const char *var, const char *val); int check_regex(const char *regex, const char *line, regmatch_t match[10]); struct odpath_t *find_path(struct odpath_t *last, const char *path, pathtype_t type, regmatch_t match[10]); void usage(const char *msg); #ifdef USE_ONENTERLEAVE void display_file(const char *path); int exec_ok(const char *path); #endif /* Definitions */ int main(int argc, const char **argv) { #ifdef USE_ONENTERLEAVE char onenter[PATH_MAX + 1]; #endif char working[PATH_MAX + 1], cwd[PATH_MAX + 1]; int len, i; const char *src = NULL, *dst = NULL, *home = NULL; if (argc < 2) usage("Not enough arguments"); for (i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-V")) { printf("This is OnDir version %s\n", VERSION); return 0; } if (argv[i][0] == '-') usage("Unknown argument"); if (!src) src = argv[i]; else if (!dst) dst = argv[i]; else usage("You have already specified src and dst directories"); } if (!dst) { getcwd(cwd, PATH_MAX); dst = cwd; } if (src[0] != '/' || dst[0] != '/') fatal("either the source or destination directory is not absolute"); root = load_conf(GLOBAL_CONF, root); if ((home = getenv("HOME"))) { snprintf(working, PATH_MAX, "%s/.ondirrc", home); root = load_conf(working, root); } /* The basic algorithm is thus: 1. Traverse up source path until it matches the lead of dest path 2. Traverse from the join to the end of dest path */ strcpy(working, src); len = strlen(working); /* Traverse up source path */ while (strncmp(working, dst, len)) { regmatch_t match[10]; struct odpath_t *p; for (p = find_path(NULL, working, PT_LEAVE, match); p; p = find_path(p, working, PT_LEAVE, match)) { char *sub; /* Construct temporary envars */ add_envar("ONDIRWD", working); for (i = 0; match[i].rm_so != -1 && i < 10; ++i) { int mlen = match[i].rm_eo - match[i].rm_so; char var[4], val[mlen]; sprintf(var, "%i", i); strncpy(val, working + match[i].rm_so, mlen); val[mlen] = 0; add_envar(var, val); } /* Expand envars */ sub = expand_envars(p->content); /* Destroy temporary envars */ putenv("ONDIRWD"); for (i = 0; match[i].rm_so != -1 && i < 10; ++i) { char var[4]; sprintf(var, "%i", i); putenv(var); } printf("%s\n", sub); free(sub); if (p->final) break; } #ifdef USE_ONENTERLEAVE snprintf(onenter, PATH_MAX, "%s/.onleave", working); if (exec_ok(onenter)) display_file(onenter); #endif while (len && working[len] != '/') --len; working[len] = 0; } if (dst[len]) ++len; /* Move up to destination */ while (dst[len] != 0) { regmatch_t match[10]; struct odpath_t *p; while (dst[len] != 0 && dst[len] != '/') ++len; strncpy(working, dst, len); working[len] = 0; for (p = find_path(NULL, working, PT_ENTER, match); p; p = find_path(p, working, PT_ENTER, match)) { char *sub; int i = 0; /* Construct temporary envars */ add_envar("ONDIRWD", working); for (i = 0; match[i].rm_so != -1 && i < 10; ++i) { int mlen = match[i].rm_eo - match[i].rm_so; char var[4], val[mlen]; sprintf(var, "%i", i); strncpy(val, working + match[i].rm_so, mlen); val[mlen] = 0; add_envar(var, val); } /* Expand envars */ sub = expand_envars(p->content); /* Destroy temporary envars */ putenv("ONDIRWD"); for (i = 0; match[i].rm_so != -1 && i < 10; ++i) { char var[4]; sprintf(var, "%i", i); putenv(var); } printf("%s", sub); free(sub); if (p->final) break; } #ifdef USE_ONENTERLEAVE snprintf(onenter, PATH_MAX, "%s/.onenter", working); if (exec_ok(onenter)) display_file(onenter); #endif if (dst[len] == '/') ++len; } return 0; } char *substitute(const char *in, const char *var, const char *val) { int inlen = strlen(in), outmax = inlen * 2, varlen = strlen(var), vallen = strlen(val), outlen = 0; char *out = calloc(1, outmax), *var1 = calloc(1, varlen + 2), *var2 = calloc(1, varlen + 4), *offset1 = NULL, *offset2 = NULL; /* Construct $VAR */ strcpy(var1, "$"); strcat(var1, var); /* Construct ${VAR} */ strcpy(var2, "${"); strcat(var2, var); strcat(var2, "}"); /* Do the replacement */ while ((offset1 = strstr(in, var1)) || (offset2 = strstr(in, var2))) { char *offset = offset1; int vlen = varlen + 1; if (!offset || (offset2 && offset2 < offset1)) offset = offset2; if (offset[1] == '{') vlen += 2; if (outlen + vlen > outmax) { outmax *= 2; out = realloc(out, outmax); } out[outlen] = 0; /* Add difference between beginning of 'in' and 'offset' */ strncat(out, in, offset - in); outlen += offset - in; in = offset; out[outlen] = 0; strcat(out, val); outlen += vallen; in += vlen; offset1 = offset2 = NULL; } strcat(out, in); return out; } /* Check if a given regex matches a given line. * * Returns: * 0 if they don't match. * 1 if they match. */ int check_regex(const char *regex, const char *line, regmatch_t match[10]) { regex_t preg; int retval = 0; if (!regex || !line) { /* FAILURE */ return (0); } if ((retval = regcomp(&preg, regex, REG_EXTENDED))) { char err_buf[512]; regerror(retval, &preg, err_buf, 512); fprintf(stderr, "ondir: regcomp failed, %s\n", err_buf); return 0; } retval = regexec(&preg, line, 10, match, 0); regfree(&preg); return retval == 0 && match[0].rm_so == 0 && match[0].rm_eo == strlen(line); } struct odpath_t *find_path(struct odpath_t *last, const char *path, pathtype_t type, regmatch_t match[10]) { struct odpath_t *i; int j; if (last) last = last->next; else last = root; for (i = last; i != NULL; i = i->next) if (i->type == type) { for (j = 0; j < i->npaths; ++j) if (!strcmp(i->paths[j], path)) { /* Emulate regex sub-pattern capturing */ match[0].rm_so = 0; match[0].rm_eo = strlen(path); match[1].rm_so = match[1].rm_eo = -1; return i; } else if (check_regex(i->paths[j], path, match)) return i; } return NULL; } int add_envar(const char *var, const char *val) { char *set = malloc(strlen(var) + strlen(val) + 2); strcpy(set, var); strcat(set, "="); strcat(set, val); return putenv(set); } #ifdef USE_ONENTERLEAVE void display_file(const char *path) { FILE *fp; if ((fp = fopen(path, "r"))) { char buffer[512]; int len; while ((len = fread(buffer, 1, 512, fp)) > 0) fwrite(buffer, len, 1, stdout); fclose(fp); } } int exec_ok(const char *path) { struct stat s; return stat(path, &s) == 0 && /* exists.. */ s.st_mode & (S_IRUSR | S_IRGRP | S_IROTH) && /* ...readable... */ s.st_uid == getuid() && /* ...owned by me... */ !(s.st_mode & (S_IWGRP | S_IWOTH)); /* ...not group/world writeable */ } #endif void usage(const char *msg) { printf( "%s\n" "usage: ondir [-V] []\n" "\n" " -V Displays version information.\n" "\n" " is the last working directory.\n" "\n" " is the current working directory. If is\n" " omitted, the current working directory is obtained via a call to getcwd().\n" "\n", msg ); exit(1); } ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/ondir.spec000066400000000000000000000022601230137037600215010ustar00rootroot00000000000000Summary: ondir is a small program to automate tasks specific to certain directories. It works by executing scripts in directories when you enter and leave them. Name: ondir Version: 0.2.2 Release: 1 Copyright: GPL Group: Development/Tools Source: ondir-%{PACKAGE_VERSION}.tar.gz BuildRoot: /var/tmp/%{name}-buildroot Packager: Alec Thomas %description OnDir automatically executes scripts in directories when you traverse them at the command line. This is useful for things like automatically changing your umask when moving into your ~/public_html directory or adding a project specific path to your PATH. %prep %setup -q %build make PREFIX=/usr CONF=/etc/ondirrc %install make DESTDIR=$RPM_BUILD_ROOT PREFIX=/usr CONF=/etc/ondirrc install %clean rm -rf $RPM_BUILD_ROOT %files %defattr(-,root,root) %doc AUTHORS README COPYING INSTALL ChangeLog ondirrc.eg scripts.sh scripts.tcsh /usr/bin/ondir /usr/man/man1/ondir.1.gz %changelog * Sun Jul 13 2003 Alec Thomas - Complete rewrite in C. No longer using automake/autoconf. Updated .spec accordingly. * Mon Jun 10 2002 Alec Thomas - Created build script and corresponding .spec file ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/ondir_prompt_hook.fish000066400000000000000000000004031230137037600241160ustar00rootroot00000000000000# copy this file to ~/.config/fish/functions function ondir_prompt_hook --on-event fish_prompt if test ! -e "$OLDONDIRWD"; set -g OLDONDIRWD /; end; if [ "$OLDONDIRWD" != "$PWD" ]; eval (ondir $OLDONDIRWD $PWD); end; set -g OLDONDIRWD "$PWD"; end ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/ondirrc.eg000066400000000000000000000004001230137037600214610ustar00rootroot00000000000000# vim:syntax=sh # I have these directories setgid, so I want my umask to allow group writes. enter /opt/music:/opt/movies # Preserve umask OLDUMASK=`umask` umask 007 # Back to normal final leave /opt/music:/opt/movies umask $OLDUMASK unset OLDUMASK ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/scripts.sh000077500000000000000000000012121230137037600215340ustar00rootroot00000000000000# # These functions override builtin BASH commands that change directories. # # This script should be added to either the system wide shell initialisation # file (/etc/profile) or a user specific initialisation file (~/.bash_profile # or ~/.profile). In addition, if you are using X, terminals you start up # should be login terminals (typically -ls, --ls or something to that effect). # cd() { builtin cd "$@" && eval "`ondir \"$OLDPWD\" \"$PWD\"`" } pushd() { builtin pushd "$@" && eval "`ondir \"$OLDPWD\" \"$PWD\"`" } popd() { builtin popd "$@" && eval "`ondir \"$OLDPWD\" \"$PWD\"`" } # Run ondir on login eval "`ondir /`" ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/scripts.tcsh000077500000000000000000000005331230137037600220700ustar00rootroot00000000000000 # Thanks go to Matthew Russell who provided this script. His usage # comments follow: # # This could be inserted into either ~/.tcshrc or # ~/.login. I don't think the "cwdcmd" alias works # on csh, the forerunner to tcsh, though. # # Run ondir on change of directory alias cwdcmd eval \`ondir -t \$owd\` # Run ondir on login eval ondir -t / ondir-55279f0366c32e4295c9f114cbee5ac7776e4d53/scripts.zsh000077500000000000000000000001471230137037600217340ustar00rootroot00000000000000eval_ondir() { eval "`ondir \"$OLDPWD\" \"$PWD\"`" } chpwd_functions=( eval_ondir $chpwd_functions )