-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rb
120 lines (100 loc) · 2.64 KB
/
main.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/env ruby
require 'optparse'
require 'fileutils'
# Command-line toolset class
class Toolset
def initialize
@options = {}
end
def parse_options
OptionParser.new do |opts|
opts.banner = "Usage: toolset [options]"
opts.on("-l", "--list", "List files in the current directory") do
@options[:list] = true
end
opts.on("-d", "--date", "Display the current date") do
@options[:date] = true
end
opts.on("-cDIR", "--create DIR", "Create a new directory") do |dir|
@options[:create] = dir
end
opts.on("-rFILE", "--remove FILE", "Remove a file or directory") do |file|
@options[:remove] = file
end
opts.on("-vFILE", "--view FILE", "View the contents of a file") do |file|
@options[:view] = file
end
opts.on("-sNAME", "--search NAME", "Search for a file by name") do |name|
@options[:search] = name
end
opts.on("-h", "--help", "Display help") do
puts opts
exit
end
end.parse!
end
def run
parse_options
if @options[:list]
list_files
elsif @options[:date]
display_date
elsif @options[:create]
create_directory(@options[:create])
elsif @options[:remove]
remove_file_or_directory(@options[:remove])
elsif @options[:view]
view_file_contents(@options[:view])
elsif @options[:search]
search_file(@options[:search])
else
puts "No valid option provided. Use -h for help."
end
end
private
def list_files
puts "Files in the current directory:"
puts Dir.entries(Dir.pwd).select { |f| !f.start_with?('.') }
end
def display_date
puts "Current date: #{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"
end
def create_directory(dir)
if Dir.exist?(dir)
puts "Directory '#{dir}' already exists."
else
Dir.mkdir(dir)
puts "Directory '#{dir}' created."
end
end
def remove_file_or_directory(file)
if File.exist?(file)
FileUtils.rm_f(file)
puts "File '#{file}' removed."
elsif Dir.exist?(file)
FileUtils.rm_rf(file)
puts "Directory '#{file}' removed."
else
puts "File or directory '#{file}' does not exist."
end
end
def view_file_contents(file)
if File.exist?(file)
puts "Contents of '#{file}':"
puts File.read(file)
else
puts "File '#{file}' does not exist."
end
end
def search_file(name)
files = Dir.glob("*#{name}*")
if files.empty?
puts "No files found matching '#{name}'."
else
puts "Files found matching '#{name}':"
puts files
end
end
end
# Run the toolset
Toolset.new.run