2 * Implements the file command for jim
4 * (c) 2008 Steve Bennett <steveb@workware.net.au>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials
15 * provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
19 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * The views and conclusions contained in the software and documentation
31 * are those of the authors and should not be interpreted as representing
32 * official policies, either expressed or implied, of the Jim Tcl Project.
34 * Based on code originally from Tcl 6.7:
36 * Copyright 1987-1991 Regents of the University of California
37 * Permission to use, copy, modify, and distribute this
38 * software and its documentation for any purpose and without
39 * fee is hereby granted, provided that the above copyright
40 * notice appear in all copies. The University of California
41 * makes no representations about the suitability of this
42 * software for any purpose. It is provided "as is" without
43 * express or implied warranty.
53 #include <jimautoconf.h>
54 #include <jim-subcmd.h>
61 #elif defined(_MSC_VER)
66 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
67 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
71 # define MAXPATHLEN JIM_PATH_LEN
74 #if defined(__MINGW32__) || defined(_MSC_VER)
81 *----------------------------------------------------------------------
85 * Given a mode word, returns a string identifying the type of a
89 * A static text string giving the file type from mode.
94 *----------------------------------------------------------------------
97 static const char *JimGetFileType(int mode
)
102 else if (S_ISDIR(mode
)) {
106 else if (S_ISCHR(mode
)) {
107 return "characterSpecial";
111 else if (S_ISBLK(mode
)) {
112 return "blockSpecial";
116 else if (S_ISFIFO(mode
)) {
121 else if (S_ISLNK(mode
)) {
126 else if (S_ISSOCK(mode
)) {
134 *----------------------------------------------------------------------
138 * This is a utility procedure that breaks out the fields of a
139 * "stat" structure and stores them in textual form into the
140 * elements of an associative array.
143 * Returns a standard Tcl return value. If an error occurs then
144 * a message is left in interp->result.
147 * Elements of the associative array given by "varName" are modified.
149 *----------------------------------------------------------------------
151 static void AppendStatElement(Jim_Interp
*interp
, Jim_Obj
*listObj
, const char *key
, jim_wide value
)
153 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, key
, -1));
154 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, value
));
157 static int StoreStatData(Jim_Interp
*interp
, Jim_Obj
*varName
, const struct stat
*sb
)
159 /* Just use a list to store the data */
160 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
162 AppendStatElement(interp
, listObj
, "dev", sb
->st_dev
);
163 AppendStatElement(interp
, listObj
, "ino", sb
->st_ino
);
164 AppendStatElement(interp
, listObj
, "mode", sb
->st_mode
);
165 AppendStatElement(interp
, listObj
, "nlink", sb
->st_nlink
);
166 AppendStatElement(interp
, listObj
, "uid", sb
->st_uid
);
167 AppendStatElement(interp
, listObj
, "gid", sb
->st_gid
);
168 AppendStatElement(interp
, listObj
, "size", sb
->st_size
);
169 AppendStatElement(interp
, listObj
, "atime", sb
->st_atime
);
170 AppendStatElement(interp
, listObj
, "mtime", sb
->st_mtime
);
171 AppendStatElement(interp
, listObj
, "ctime", sb
->st_ctime
);
172 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, "type", -1));
173 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, JimGetFileType((int)sb
->st_mode
), -1));
175 /* Was a variable specified? */
178 objPtr
= Jim_GetVariable(interp
, varName
, JIM_NONE
);
186 objPtr
= Jim_DictMerge(interp
, 2, objv
);
187 if (objPtr
== NULL
) {
188 /* This message matches the one from Tcl */
189 Jim_SetResultFormatted(interp
, "can't set \"%#s(dev)\": variable isn't array", varName
);
190 Jim_FreeNewObj(interp
, listObj
);
194 Jim_InvalidateStringRep(objPtr
);
196 Jim_FreeNewObj(interp
, listObj
);
199 Jim_SetVariable(interp
, varName
, listObj
);
202 /* And also return the value */
203 Jim_SetResult(interp
, listObj
);
208 static int file_cmd_dirname(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
210 const char *path
= Jim_String(argv
[0]);
211 const char *p
= strrchr(path
, '/');
213 if (!p
&& path
[0] == '.' && path
[1] == '.' && path
[2] == '\0') {
214 Jim_SetResultString(interp
, "..", -1);
216 Jim_SetResultString(interp
, ".", -1);
218 else if (p
== path
) {
219 Jim_SetResultString(interp
, "/", -1);
221 else if (ISWINDOWS
&& p
[-1] == ':') {
223 Jim_SetResultString(interp
, path
, p
- path
+ 1);
226 Jim_SetResultString(interp
, path
, p
- path
);
231 static int file_cmd_rootname(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
233 const char *path
= Jim_String(argv
[0]);
234 const char *lastSlash
= strrchr(path
, '/');
235 const char *p
= strrchr(path
, '.');
237 if (p
== NULL
|| (lastSlash
!= NULL
&& lastSlash
> p
)) {
238 Jim_SetResult(interp
, argv
[0]);
241 Jim_SetResultString(interp
, path
, p
- path
);
246 static int file_cmd_extension(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
248 const char *path
= Jim_String(argv
[0]);
249 const char *lastSlash
= strrchr(path
, '/');
250 const char *p
= strrchr(path
, '.');
252 if (p
== NULL
|| (lastSlash
!= NULL
&& lastSlash
>= p
)) {
255 Jim_SetResultString(interp
, p
, -1);
259 static int file_cmd_tail(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
261 const char *path
= Jim_String(argv
[0]);
262 const char *lastSlash
= strrchr(path
, '/');
265 Jim_SetResultString(interp
, lastSlash
+ 1, -1);
268 Jim_SetResult(interp
, argv
[0]);
273 static int file_cmd_normalize(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
276 const char *path
= Jim_String(argv
[0]);
277 char *newname
= Jim_Alloc(MAXPATHLEN
+ 1);
279 if (realpath(path
, newname
)) {
280 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, newname
, -1));
285 Jim_SetResultFormatted(interp
, "can't normalize \"%#s\": %s", argv
[0], strerror(errno
));
289 Jim_SetResultString(interp
, "Not implemented", -1);
294 static int file_cmd_join(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
297 char *newname
= Jim_Alloc(MAXPATHLEN
+ 1);
298 char *last
= newname
;
302 /* Simple implementation for now */
303 for (i
= 0; i
< argc
; i
++) {
305 const char *part
= Jim_GetString(argv
[i
], &len
);
308 /* Absolute component, so go back to the start */
311 else if (ISWINDOWS
&& strchr(part
, ':')) {
312 /* Absolute component on mingw, so go back to the start */
315 else if (part
[0] == '.') {
316 if (part
[1] == '/') {
320 else if (part
[1] == 0 && last
!= newname
) {
321 /* Adding '.' to an existing path does nothing */
326 /* Add a slash if needed */
327 if (last
!= newname
&& last
[-1] != '/') {
332 if (last
+ len
- newname
>= MAXPATHLEN
) {
334 Jim_SetResultString(interp
, "Path too long", -1);
337 memcpy(last
, part
, len
);
341 /* Remove a slash if needed */
342 if (last
> newname
+ 1 && last
[-1] == '/') {
343 /* but on on Windows, leave the trailing slash on "c:/ " */
344 if (!ISWINDOWS
|| !(last
> newname
+ 2 && last
[-2] == ':')) {
352 /* Probably need to handle some special cases ... */
354 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, newname
, last
- newname
));
359 static int file_access(Jim_Interp
*interp
, Jim_Obj
*filename
, int mode
)
361 Jim_SetResultBool(interp
, access(Jim_String(filename
), mode
) != -1);
366 static int file_cmd_readable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
368 return file_access(interp
, argv
[0], R_OK
);
371 static int file_cmd_writable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
373 return file_access(interp
, argv
[0], W_OK
);
376 static int file_cmd_executable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
379 return file_access(interp
, argv
[0], X_OK
);
381 /* If no X_OK, just assume true. */
382 Jim_SetResultBool(interp
, 1);
387 static int file_cmd_exists(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
389 return file_access(interp
, argv
[0], F_OK
);
392 static int file_cmd_delete(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
394 int force
= Jim_CompareStringImmediate(interp
, argv
[0], "-force");
396 if (force
|| Jim_CompareStringImmediate(interp
, argv
[0], "--")) {
402 const char *path
= Jim_String(argv
[0]);
404 if (unlink(path
) == -1 && errno
!= ENOENT
) {
405 if (rmdir(path
) == -1) {
406 /* Maybe try using the script helper */
407 if (!force
|| Jim_EvalPrefix(interp
, "file delete force", 1, argv
) != JIM_OK
) {
408 Jim_SetResultFormatted(interp
, "couldn't delete file \"%s\": %s", path
,
419 #ifdef HAVE_MKDIR_ONE_ARG
420 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME)
422 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME, 0755)
426 * Create directory, creating all intermediate paths if necessary.
428 * Returns 0 if OK or -1 on failure (and sets errno)
430 * Note: The path may be modified.
432 static int mkdir_all(char *path
)
436 /* First time just try to make the dir */
440 /* Must have failed the first time, so recursively make the parent and try again */
442 char *slash
= strrchr(path
, '/');
444 if (slash
&& slash
!= path
) {
446 if (mkdir_all(path
) != 0) {
453 if (MKDIR_DEFAULT(path
) == 0) {
456 if (errno
== ENOENT
) {
457 /* Create the parent and try again */
460 /* Maybe it already exists as a directory */
461 if (errno
== EEXIST
) {
464 if (stat(path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
)) {
476 static int file_cmd_mkdir(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
479 char *path
= Jim_StrDup(Jim_String(argv
[0]));
480 int rc
= mkdir_all(path
);
484 Jim_SetResultFormatted(interp
, "can't create directory \"%#s\": %s", argv
[0],
493 static int file_cmd_tempfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
495 int fd
= Jim_MakeTempFile(interp
, (argc
>= 1) ? Jim_String(argv
[0]) : NULL
);
505 static int file_cmd_rename(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
512 if (!Jim_CompareStringImmediate(interp
, argv
[0], "-force")) {
520 source
= Jim_String(argv
[0]);
521 dest
= Jim_String(argv
[1]);
523 if (!force
&& access(dest
, F_OK
) == 0) {
524 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": target exists", argv
[0],
529 if (rename(source
, dest
) != 0) {
530 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": %s", argv
[0], argv
[1],
538 #if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
539 static int file_cmd_link(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
544 static const char * const options
[] = { "-hard", "-symbolic", NULL
};
545 enum { OPT_HARD
, OPT_SYMBOLIC
, };
546 int option
= OPT_HARD
;
549 if (Jim_GetEnum(interp
, argv
[0], options
, &option
, NULL
, JIM_ENUM_ABBREV
| JIM_ERRMSG
) != JIM_OK
) {
556 dest
= Jim_String(argv
[0]);
557 source
= Jim_String(argv
[1]);
559 if (option
== OPT_HARD
) {
560 ret
= link(source
, dest
);
563 ret
= symlink(source
, dest
);
567 Jim_SetResultFormatted(interp
, "error linking \"%#s\" to \"%#s\": %s", argv
[0], argv
[1],
576 static int file_stat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
578 const char *path
= Jim_String(filename
);
580 if (stat(path
, sb
) == -1) {
581 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
588 static int file_lstat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
590 const char *path
= Jim_String(filename
);
592 if (lstat(path
, sb
) == -1) {
593 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
599 #define file_lstat file_stat
602 static int file_cmd_atime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
606 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
609 Jim_SetResultInt(interp
, sb
.st_atime
);
613 static int file_cmd_mtime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
620 struct timeval times
[2];
622 if (Jim_GetWide(interp
, argv
[1], &newtime
) != JIM_OK
) {
626 times
[1].tv_sec
= times
[0].tv_sec
= newtime
;
627 times
[1].tv_usec
= times
[0].tv_usec
= 0;
629 if (utimes(Jim_String(argv
[0]), times
) != 0) {
630 Jim_SetResultFormatted(interp
, "can't set time on \"%#s\": %s", argv
[0], strerror(errno
));
634 Jim_SetResultString(interp
, "Not implemented", -1);
638 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
641 Jim_SetResultInt(interp
, sb
.st_mtime
);
645 static int file_cmd_copy(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
647 return Jim_EvalPrefix(interp
, "file copy", argc
, argv
);
650 static int file_cmd_size(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
654 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
657 Jim_SetResultInt(interp
, sb
.st_size
);
661 static int file_cmd_isdirectory(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
666 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
667 ret
= S_ISDIR(sb
.st_mode
);
669 Jim_SetResultInt(interp
, ret
);
673 static int file_cmd_isfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
678 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
679 ret
= S_ISREG(sb
.st_mode
);
681 Jim_SetResultInt(interp
, ret
);
686 static int file_cmd_owned(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
691 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
692 ret
= (geteuid() == sb
.st_uid
);
694 Jim_SetResultInt(interp
, ret
);
699 #if defined(HAVE_READLINK)
700 static int file_cmd_readlink(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
702 const char *path
= Jim_String(argv
[0]);
703 char *linkValue
= Jim_Alloc(MAXPATHLEN
+ 1);
705 int linkLength
= readlink(path
, linkValue
, MAXPATHLEN
);
707 if (linkLength
== -1) {
709 Jim_SetResultFormatted(interp
, "couldn't readlink \"%#s\": %s", argv
[0], strerror(errno
));
712 linkValue
[linkLength
] = 0;
713 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, linkValue
, linkLength
));
718 static int file_cmd_type(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
722 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
725 Jim_SetResultString(interp
, JimGetFileType((int)sb
.st_mode
), -1);
730 static int file_cmd_lstat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
734 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
737 return StoreStatData(interp
, argc
== 2 ? argv
[1] : NULL
, &sb
);
740 #define file_cmd_lstat file_cmd_stat
743 static int file_cmd_stat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
747 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
750 return StoreStatData(interp
, argc
== 2 ? argv
[1] : NULL
, &sb
);
753 static const jim_subcmd_type file_command_table
[] = {
759 /* Description: Last access time */
766 /* Description: Get or set last modification time */
769 "?-force? source dest",
773 /* Description: Copy source file to destination file */
780 /* Description: Directory part of the name */
787 /* Description: Name without any extension */
794 /* Description: Last extension including the dot */
801 /* Description: Last component of the name */
808 /* Description: Normalized path of name */
815 /* Description: Join multiple path components */
822 /* Description: Is file readable */
829 /* Description: Is file writable */
836 /* Description: Is file executable */
843 /* Description: Does file exist */
846 "?-force|--? name ...",
850 /* Description: Deletes the files or directories (must be empty unless -force) */
857 /* Description: Creates the directories */
864 /* Description: Creates a temporary filename */
867 "?-force? source dest",
871 /* Description: Renames a file */
873 #if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
875 "?-symbolic|-hard? newname target",
879 /* Description: Creates a hard or soft link */
882 #if defined(HAVE_READLINK)
888 /* Description: Value of the symbolic link */
896 /* Description: Size of file */
903 /* Description: Returns results of stat, and may store in var array */
910 /* Description: Returns results of lstat, and may store in var array */
917 /* Description: Returns type of the file */
925 /* Description: Returns 1 if owned by the current owner */
930 file_cmd_isdirectory
,
933 /* Description: Returns 1 if name is a directory */
940 /* Description: Returns 1 if name is a file */
947 static int Jim_CdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
952 Jim_WrongNumArgs(interp
, 1, argv
, "dirname");
956 path
= Jim_String(argv
[1]);
958 if (chdir(path
) != 0) {
959 Jim_SetResultFormatted(interp
, "couldn't change working directory to \"%s\": %s", path
,
966 static int Jim_PwdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
968 char *cwd
= Jim_Alloc(MAXPATHLEN
);
970 if (getcwd(cwd
, MAXPATHLEN
) == NULL
) {
971 Jim_SetResultString(interp
, "Failed to get pwd", -1);
975 else if (ISWINDOWS
) {
976 /* Try to keep backslashes out of paths */
978 while ((p
= strchr(p
, '\\')) != NULL
) {
983 Jim_SetResultString(interp
, cwd
, -1);
989 int Jim_fileInit(Jim_Interp
*interp
)
991 if (Jim_PackageProvide(interp
, "file", "1.0", JIM_ERRMSG
))
994 Jim_CreateCommand(interp
, "file", Jim_SubCmdProc
, (void *)file_command_table
, NULL
);
995 Jim_CreateCommand(interp
, "pwd", Jim_PwdCmd
, NULL
, NULL
);
996 Jim_CreateCommand(interp
, "cd", Jim_CdCmd
, NULL
, NULL
);