01: /*
02: * basename.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.InputStream;
12: import java.io.DataInputStream;
13: import java.io.File;
14: import java.io.IOException;
15: import pnuts.lang.Context;
16: import pnuts.lang.PnutsFunction;
17: import pnuts.lang.PnutsException;
18:
19: public class basename extends PnutsFunction {
20:
21: public basename() {
22: super ("basename");
23: }
24:
25: public boolean defined(int narg) {
26: return (narg == 1 || narg == 2);
27: }
28:
29: protected Object exec(Object[] args, Context context) {
30: int nargs = args.length;
31: if (nargs == 1) {
32: String name = null;
33: Object arg = args[0];
34: if (arg instanceof File) {
35: name = ((File) arg).getName();
36: } else if (arg instanceof String) {
37: name = new File((String) arg).getName();
38: } else {
39: throw new IllegalArgumentException(String.valueOf(arg));
40: }
41: int idx = name.lastIndexOf('.');
42: if (idx > 0) {
43: return name.substring(0, idx);
44: } else {
45: return name;
46: }
47: } else if (nargs == 2) {
48: Object arg0 = args[0];
49: Object arg1 = args[1];
50: String name;
51: if (arg0 instanceof String) {
52: name = new File((String) arg0).getName();
53: } else if (arg0 instanceof File) {
54: name = ((File) arg0).getName();
55: } else {
56: throw new IllegalArgumentException(String.valueOf(arg0));
57: }
58: String suffix = (String) arg1;
59: if (name.endsWith(suffix)) {
60: return name.substring(0, name.length()
61: - suffix.length());
62: } else {
63: return name;
64: }
65: } else {
66: undefined(args, context);
67: return null;
68: }
69: }
70:
71: public String toString() {
72: return "function basename(filename {, suffix })";
73: }
74: }
|