01: /*
02: * dirname.java
03: *
04: * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import java.io.File;
12: import pnuts.lang.Context;
13: import pnuts.lang.PnutsFunction;
14:
15: public class dirname extends PnutsFunction {
16: private final static char FILE_SEPARATOR = '/';
17: private final static boolean useBackslash = ("\\"
18: .equals(getProperty("file.separator")));
19:
20: public dirname() {
21: super ("dirname");
22: }
23:
24: public boolean defined(int narg) {
25: return (narg == 1);
26: }
27:
28: protected Object exec(Object[] args, Context context) {
29: int nargs = args.length;
30: if (nargs == 1) {
31: String name = null;
32: Object arg = args[0];
33: if (arg instanceof File) {
34: name = ((File) arg).getName();
35: } else if (arg instanceof String) {
36: name = (String) arg;
37: } else {
38: throw new IllegalArgumentException(String.valueOf(arg));
39: }
40: int idx = name.length();
41: idx--;
42: char ch = name.charAt(idx);
43: if (ch == FILE_SEPARATOR || (useBackslash && ch == '\\')) {
44: idx--;
45: }
46: while (idx >= 0) {
47: ch = name.charAt(idx);
48: if (ch == FILE_SEPARATOR
49: || (useBackslash && ch == '\\')) {
50: return name.substring(0, idx);
51: }
52: idx--;
53: }
54: return name;
55: } else {
56: undefined(args, context);
57: return null;
58: }
59: }
60:
61: public String toString() {
62: return "function dirname(filename)";
63: }
64: }
|