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? */
177 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, varName
, JIM_NONE
);
179 if (Jim_DictSize(interp
, objPtr
) < 0) {
180 /* This message matches the one from Tcl */
181 Jim_SetResultFormatted(interp
, "can't set \"%#s(dev)\": variable isn't array", varName
);
182 Jim_FreeNewObj(interp
, listObj
);
186 if (Jim_IsShared(objPtr
))
187 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
189 /* Just cheat here and append as a list and convert to a dict */
190 Jim_ListAppendList(interp
, objPtr
, listObj
);
191 Jim_DictSize(interp
, objPtr
);
192 Jim_InvalidateStringRep(objPtr
);
194 Jim_FreeNewObj(interp
, listObj
);
197 Jim_SetVariable(interp
, varName
, listObj
);
200 /* And also return the value */
201 Jim_SetResult(interp
, listObj
);
206 static int file_cmd_dirname(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
208 const char *path
= Jim_String(argv
[0]);
209 const char *p
= strrchr(path
, '/');
211 if (!p
&& path
[0] == '.' && path
[1] == '.' && path
[2] == '\0') {
212 Jim_SetResultString(interp
, "..", -1);
214 Jim_SetResultString(interp
, ".", -1);
216 else if (p
== path
) {
217 Jim_SetResultString(interp
, "/", -1);
219 else if (ISWINDOWS
&& p
[-1] == ':') {
221 Jim_SetResultString(interp
, path
, p
- path
+ 1);
224 Jim_SetResultString(interp
, path
, p
- path
);
229 static int file_cmd_rootname(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
231 const char *path
= Jim_String(argv
[0]);
232 const char *lastSlash
= strrchr(path
, '/');
233 const char *p
= strrchr(path
, '.');
235 if (p
== NULL
|| (lastSlash
!= NULL
&& lastSlash
> p
)) {
236 Jim_SetResult(interp
, argv
[0]);
239 Jim_SetResultString(interp
, path
, p
- path
);
244 static int file_cmd_extension(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
246 const char *path
= Jim_String(argv
[0]);
247 const char *lastSlash
= strrchr(path
, '/');
248 const char *p
= strrchr(path
, '.');
250 if (p
== NULL
|| (lastSlash
!= NULL
&& lastSlash
>= p
)) {
253 Jim_SetResultString(interp
, p
, -1);
257 static int file_cmd_tail(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
259 const char *path
= Jim_String(argv
[0]);
260 const char *lastSlash
= strrchr(path
, '/');
263 Jim_SetResultString(interp
, lastSlash
+ 1, -1);
266 Jim_SetResult(interp
, argv
[0]);
271 static int file_cmd_normalize(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
274 const char *path
= Jim_String(argv
[0]);
275 char *newname
= Jim_Alloc(MAXPATHLEN
+ 1);
277 if (realpath(path
, newname
)) {
278 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, newname
, -1));
283 Jim_SetResultFormatted(interp
, "can't normalize \"%#s\": %s", argv
[0], strerror(errno
));
287 Jim_SetResultString(interp
, "Not implemented", -1);
292 static int file_cmd_join(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
295 char *newname
= Jim_Alloc(MAXPATHLEN
+ 1);
296 char *last
= newname
;
300 /* Simple implementation for now */
301 for (i
= 0; i
< argc
; i
++) {
303 const char *part
= Jim_GetString(argv
[i
], &len
);
306 /* Absolute component, so go back to the start */
309 else if (ISWINDOWS
&& strchr(part
, ':')) {
310 /* Absolute component on mingw, so go back to the start */
313 else if (part
[0] == '.') {
314 if (part
[1] == '/') {
318 else if (part
[1] == 0 && last
!= newname
) {
319 /* Adding '.' to an existing path does nothing */
324 /* Add a slash if needed */
325 if (last
!= newname
&& last
[-1] != '/') {
330 if (last
+ len
- newname
>= MAXPATHLEN
) {
332 Jim_SetResultString(interp
, "Path too long", -1);
335 memcpy(last
, part
, len
);
339 /* Remove a slash if needed */
340 if (last
> newname
+ 1 && last
[-1] == '/') {
341 /* but on on Windows, leave the trailing slash on "c:/ " */
342 if (!ISWINDOWS
|| !(last
> newname
+ 2 && last
[-2] == ':')) {
350 /* Probably need to handle some special cases ... */
352 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, newname
, last
- newname
));
357 static int file_access(Jim_Interp
*interp
, Jim_Obj
*filename
, int mode
)
359 Jim_SetResultBool(interp
, access(Jim_String(filename
), mode
) != -1);
364 static int file_cmd_readable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
366 return file_access(interp
, argv
[0], R_OK
);
369 static int file_cmd_writable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
371 return file_access(interp
, argv
[0], W_OK
);
374 static int file_cmd_executable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
377 return file_access(interp
, argv
[0], X_OK
);
379 /* If no X_OK, just assume true. */
380 Jim_SetResultBool(interp
, 1);
385 static int file_cmd_exists(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
387 return file_access(interp
, argv
[0], F_OK
);
390 static int file_cmd_delete(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
392 int force
= Jim_CompareStringImmediate(interp
, argv
[0], "-force");
394 if (force
|| Jim_CompareStringImmediate(interp
, argv
[0], "--")) {
400 const char *path
= Jim_String(argv
[0]);
402 if (unlink(path
) == -1 && errno
!= ENOENT
) {
403 if (rmdir(path
) == -1) {
404 /* Maybe try using the script helper */
405 if (!force
|| Jim_EvalPrefix(interp
, "file delete force", 1, argv
) != JIM_OK
) {
406 Jim_SetResultFormatted(interp
, "couldn't delete file \"%s\": %s", path
,
417 #ifdef HAVE_MKDIR_ONE_ARG
418 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME)
420 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME, 0755)
424 * Create directory, creating all intermediate paths if necessary.
426 * Returns 0 if OK or -1 on failure (and sets errno)
428 * Note: The path may be modified.
430 static int mkdir_all(char *path
)
434 /* First time just try to make the dir */
438 /* Must have failed the first time, so recursively make the parent and try again */
440 char *slash
= strrchr(path
, '/');
442 if (slash
&& slash
!= path
) {
444 if (mkdir_all(path
) != 0) {
451 if (MKDIR_DEFAULT(path
) == 0) {
454 if (errno
== ENOENT
) {
455 /* Create the parent and try again */
458 /* Maybe it already exists as a directory */
459 if (errno
== EEXIST
) {
462 if (stat(path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
)) {
474 static int file_cmd_mkdir(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
477 char *path
= Jim_StrDup(Jim_String(argv
[0]));
478 int rc
= mkdir_all(path
);
482 Jim_SetResultFormatted(interp
, "can't create directory \"%#s\": %s", argv
[0],
491 static int file_cmd_tempfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
493 int fd
= Jim_MakeTempFile(interp
, (argc
>= 1) ? Jim_String(argv
[0]) : NULL
);
503 static int file_cmd_rename(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
510 if (!Jim_CompareStringImmediate(interp
, argv
[0], "-force")) {
518 source
= Jim_String(argv
[0]);
519 dest
= Jim_String(argv
[1]);
521 if (!force
&& access(dest
, F_OK
) == 0) {
522 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": target exists", argv
[0],
527 if (rename(source
, dest
) != 0) {
528 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": %s", argv
[0], argv
[1],
536 #if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
537 static int file_cmd_link(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
542 static const char * const options
[] = { "-hard", "-symbolic", NULL
};
543 enum { OPT_HARD
, OPT_SYMBOLIC
, };
544 int option
= OPT_HARD
;
547 if (Jim_GetEnum(interp
, argv
[0], options
, &option
, NULL
, JIM_ENUM_ABBREV
| JIM_ERRMSG
) != JIM_OK
) {
554 dest
= Jim_String(argv
[0]);
555 source
= Jim_String(argv
[1]);
557 if (option
== OPT_HARD
) {
558 ret
= link(source
, dest
);
561 ret
= symlink(source
, dest
);
565 Jim_SetResultFormatted(interp
, "error linking \"%#s\" to \"%#s\": %s", argv
[0], argv
[1],
574 static int file_stat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
576 const char *path
= Jim_String(filename
);
578 if (stat(path
, sb
) == -1) {
579 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
586 static int file_lstat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
588 const char *path
= Jim_String(filename
);
590 if (lstat(path
, sb
) == -1) {
591 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
597 #define file_lstat file_stat
600 static int file_cmd_atime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
604 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
607 Jim_SetResultInt(interp
, sb
.st_atime
);
611 static int file_cmd_mtime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
618 struct timeval times
[2];
620 if (Jim_GetWide(interp
, argv
[1], &newtime
) != JIM_OK
) {
624 times
[1].tv_sec
= times
[0].tv_sec
= newtime
;
625 times
[1].tv_usec
= times
[0].tv_usec
= 0;
627 if (utimes(Jim_String(argv
[0]), times
) != 0) {
628 Jim_SetResultFormatted(interp
, "can't set time on \"%#s\": %s", argv
[0], strerror(errno
));
632 Jim_SetResultString(interp
, "Not implemented", -1);
636 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
639 Jim_SetResultInt(interp
, sb
.st_mtime
);
643 static int file_cmd_copy(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
645 return Jim_EvalPrefix(interp
, "file copy", argc
, argv
);
648 static int file_cmd_size(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
652 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
655 Jim_SetResultInt(interp
, sb
.st_size
);
659 static int file_cmd_isdirectory(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
664 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
665 ret
= S_ISDIR(sb
.st_mode
);
667 Jim_SetResultInt(interp
, ret
);
671 static int file_cmd_isfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
676 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
677 ret
= S_ISREG(sb
.st_mode
);
679 Jim_SetResultInt(interp
, ret
);
684 static int file_cmd_owned(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
689 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
690 ret
= (geteuid() == sb
.st_uid
);
692 Jim_SetResultInt(interp
, ret
);
697 #if defined(HAVE_READLINK)
698 static int file_cmd_readlink(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
700 const char *path
= Jim_String(argv
[0]);
701 char *linkValue
= Jim_Alloc(MAXPATHLEN
+ 1);
703 int linkLength
= readlink(path
, linkValue
, MAXPATHLEN
);
705 if (linkLength
== -1) {
707 Jim_SetResultFormatted(interp
, "couldn't readlink \"%#s\": %s", argv
[0], strerror(errno
));
710 linkValue
[linkLength
] = 0;
711 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, linkValue
, linkLength
));
716 static int file_cmd_type(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
720 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
723 Jim_SetResultString(interp
, JimGetFileType((int)sb
.st_mode
), -1);
728 static int file_cmd_lstat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
732 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
735 return StoreStatData(interp
, argc
== 2 ? argv
[1] : NULL
, &sb
);
738 #define file_cmd_lstat file_cmd_stat
741 static int file_cmd_stat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
745 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
748 return StoreStatData(interp
, argc
== 2 ? argv
[1] : NULL
, &sb
);
751 static const jim_subcmd_type file_command_table
[] = {
757 /* Description: Last access time */
764 /* Description: Get or set last modification time */
767 "?-force? source dest",
771 /* Description: Copy source file to destination file */
778 /* Description: Directory part of the name */
785 /* Description: Name without any extension */
792 /* Description: Last extension including the dot */
799 /* Description: Last component of the name */
806 /* Description: Normalized path of name */
813 /* Description: Join multiple path components */
820 /* Description: Is file readable */
827 /* Description: Is file writable */
834 /* Description: Is file executable */
841 /* Description: Does file exist */
844 "?-force|--? name ...",
848 /* Description: Deletes the files or directories (must be empty unless -force) */
855 /* Description: Creates the directories */
862 /* Description: Creates a temporary filename */
865 "?-force? source dest",
869 /* Description: Renames a file */
871 #if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
873 "?-symbolic|-hard? newname target",
877 /* Description: Creates a hard or soft link */
880 #if defined(HAVE_READLINK)
886 /* Description: Value of the symbolic link */
894 /* Description: Size of file */
901 /* Description: Returns results of stat, and may store in var array */
908 /* Description: Returns results of lstat, and may store in var array */
915 /* Description: Returns type of the file */
923 /* Description: Returns 1 if owned by the current owner */
928 file_cmd_isdirectory
,
931 /* Description: Returns 1 if name is a directory */
938 /* Description: Returns 1 if name is a file */
945 static int Jim_CdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
950 Jim_WrongNumArgs(interp
, 1, argv
, "dirname");
954 path
= Jim_String(argv
[1]);
956 if (chdir(path
) != 0) {
957 Jim_SetResultFormatted(interp
, "couldn't change working directory to \"%s\": %s", path
,
964 static int Jim_PwdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
966 char *cwd
= Jim_Alloc(MAXPATHLEN
);
968 if (getcwd(cwd
, MAXPATHLEN
) == NULL
) {
969 Jim_SetResultString(interp
, "Failed to get pwd", -1);
973 else if (ISWINDOWS
) {
974 /* Try to keep backslashes out of paths */
976 while ((p
= strchr(p
, '\\')) != NULL
) {
981 Jim_SetResultString(interp
, cwd
, -1);
987 int Jim_fileInit(Jim_Interp
*interp
)
989 if (Jim_PackageProvide(interp
, "file", "1.0", JIM_ERRMSG
))
992 Jim_CreateCommand(interp
, "file", Jim_SubCmdProc
, (void *)file_command_table
, NULL
);
993 Jim_CreateCommand(interp
, "pwd", Jim_PwdCmd
, NULL
, NULL
);
994 Jim_CreateCommand(interp
, "cd", Jim_CdCmd
, NULL
, NULL
);