repo
string
commit
string
message
string
diff
string
Spacerat/BlitzIRC
8ccc9e3f94969d3ec9a3e4721ff570eac69223ce
Joins a channel for testing purposes.
diff --git a/SpaceBot/spacebot.bmx b/SpaceBot/spacebot.bmx index 14abb3d..79a664c 100644 --- a/SpaceBot/spacebot.bmx +++ b/SpaceBot/spacebot.bmx @@ -1,25 +1,25 @@ SuperStrict Framework brl.blitz Import "irc.bmx" Import "Modules/debug.bmx" Global SBConfig:IRCClientConfig = New IRCClientConfig Global SBClient:IRCClient = New IRCClient SBConfig.SetServer("irc.ajaxlife.net") SBConfig.SetNick("SpaceBot") SBConfig.SetName("SpaceBot") SBConfig.SetIdent("spacebot") SBClient.Connect(SBConfig) SBClient.BeginThread() - +SBClient.Send("JOIN #spacebot") Global terminate:Int = False While Not terminate If Input() = "" terminate = 1 EndWhile
Spacerat/BlitzIRC
0e93cf870024a050b1b85711033938f031662b23
Fixed a silly bug. The bot connects now.
diff --git a/SpaceBot/irc.bmx b/SpaceBot/irc.bmx index 7e82b4a..afa5a43 100644 --- a/SpaceBot/irc.bmx +++ b/SpaceBot/irc.bmx @@ -1,185 +1,185 @@ SuperStrict Import brl.threads Import brl.socketstream Import brl.textstream Import brl.hook Rem bbdoc: IRC Event object about: This object is passed to IRC hook functions in the same way TEvent is used by BRL. EndRem Type IRCEvent Field _hookid:Int Field _client:IRCClient Field _data:String Rem bbdoc: Create an IRC Event object about: id is the hook id. data is the message as a string. returns: The new IRCEvent EndRem Function Create:IRCEvent(id:Int, client:IRCClient, data:String) If Not client Throw "IRC Event must have a valid client" Local n:IRCEvent = New IRCEvent n._hookid = id n._client = client n._data = data Return n EndFunction '#Region Get/Set methods Rem bbdoc: Get the message data EndRem Method GetData:String() Return _data End Method '#End Region End Type Rem bbdoc: IRC Configuration struct about: Stores information about a network and connection info for it. EndRem Type IRCClientConfig Field _Network:String Field _Port:Int = 6667 Field _Nick:String Field _Name:String Field _Ident:String '#Region Get/Set methods Rem bbdoc: Set the server and port EndRem Method SetServer(network:String, port:Int = 6667) _Network = network _Port = port End Method Rem bbdoc: Set the nick EndRem Method SetNick(nick:String) _Nick = nick End Method Rem bbdoc: Set the real name EndRem Method SetName(name:String) _Name = name End Method Rem bbdoc: Set the ident EndRem Method SetIdent(ident:String) _Ident = ident End Method '#End Region End Type Rem bbdoc: The main IRC client type EndRem Type IRCClient Global OUTHOOK:Int = AllocHookId() Global INHOOK:Int = AllocHookId() Field _socket:TSocket Field _stream:TSocketStream Field _utf8:TTextStream Field _running:Int = False Rem bbdoc: Connect to a server EndRem Method Connect:Int(config:IRCClientConfig) 'Attempt a TCP connection _socket = TSocket.CreateTCP() _socket.Connect(HostIp(config._Network), config._Port) _stream = CreateSocketStream(_socket) _utf8 = TTextStream.Create(_stream, TTextStream.UTF8) Send("NICK " + config._Nick) - Send("USER " + config._Nick + "8 * :" + config._Name) + Send("USER " + config._Nick + " 8 * :" + config._Name) _running = True EndMethod Rem bbdoc: Start the thread EndRem Method BeginThread:TThread() ?threaded Return TThread.Create(IRCClientThread, Self) ? Throw "ERROR: Cannot create an IRC Client thread in non-threaded mode!" End Method Rem bbdoc: Send a string to the server EndRem Method Send(line:String, utf8:Int = True) RunIRCHookThread(IRCEvent.Create(OUTHOOK, Self, line)) If utf8 _utf8.WriteLine(line) Else _stream.WriteLine(line) EndIf End Method Rem bbdoc: Execute a client cycle. EndRem Method Run() While Not _stream.Eof() Local line:String = _stream.ReadLine() RunIRCHookThread(IRCEvent.Create(INHOOK, Self, line)) Wend End Method '#Region Get/Set/Is methods Method IsRunning:Int() Return _running End Method '#End Region EndType Rem bbdoc: Run an IRC Event in a new thread. returns: The new thread EndRem Function RunIRCHookThread:TThread(event:IRCEvent) ?threaded Return TThread.Create(IRCHookThread, event) ?Not threaded IRCHookThread(event) ? EndFunction Function IRCClientThread:Object(data:Object) Local client:IRCClient = IRCClient(data) If Not client Return Null While client.IsRunning() client.Run() Wend End Function Function IRCHookThread:Object(data:Object) Local event:IRCEvent = IRCEvent(data) If (event) Return RunHooks(event._hookid, event) End If End Function
Spacerat/BlitzIRC
a40dcfcf83371290ed0b88645178f8ed97a7bc1e
Renamed /Plugins/ to /Modules/
diff --git a/SpaceBot/Plugins/debug.bmx b/SpaceBot/Modules/debug.bmx similarity index 100% rename from SpaceBot/Plugins/debug.bmx rename to SpaceBot/Modules/debug.bmx diff --git a/SpaceBot/spacebot.bmx b/SpaceBot/spacebot.bmx index 2a20ce0..14abb3d 100644 --- a/SpaceBot/spacebot.bmx +++ b/SpaceBot/spacebot.bmx @@ -1,25 +1,25 @@ SuperStrict Framework brl.blitz Import "irc.bmx" -Import "plugins/debug.bmx" +Import "Modules/debug.bmx" Global SBConfig:IRCClientConfig = New IRCClientConfig Global SBClient:IRCClient = New IRCClient SBConfig.SetServer("irc.ajaxlife.net") SBConfig.SetNick("SpaceBot") SBConfig.SetName("SpaceBot") SBConfig.SetIdent("spacebot") SBClient.Connect(SBConfig) SBClient.BeginThread() Global terminate:Int = False While Not terminate If Input() = "" terminate = 1 EndWhile
Spacerat/BlitzIRC
10beecfc0134da0a6d3abc519693299720319b49
.gitignore file, for ignoring annoying blitz files.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2a32629 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# ignore build results: +*.[ai] +.bmx/ +*.exe +# generated docs +doc/ +# backup files produced by MaxIDE +*.bak +*~ +
Spacerat/BlitzIRC
ff2e1c1406c8bb6c03cab84c294aeddcddfd901b
Added more documentation and foldable regions.
diff --git a/SpaceBot/irc.bmx b/SpaceBot/irc.bmx index cbe3e86..7e82b4a 100644 --- a/SpaceBot/irc.bmx +++ b/SpaceBot/irc.bmx @@ -1,144 +1,185 @@ SuperStrict Import brl.threads Import brl.socketstream Import brl.textstream Import brl.hook +Rem +bbdoc: IRC Event object +about: This object is passed to IRC hook functions in the same way TEvent is used by BRL. +EndRem Type IRCEvent Field _hookid:Int Field _client:IRCClient Field _data:String + Rem + bbdoc: Create an IRC Event object + about: id is the hook id. data is the message as a string. + returns: The new IRCEvent + EndRem Function Create:IRCEvent(id:Int, client:IRCClient, data:String) If Not client Throw "IRC Event must have a valid client" Local n:IRCEvent = New IRCEvent n._hookid = id n._client = client n._data = data Return n EndFunction +'#Region Get/Set methods + + Rem + bbdoc: Get the message data + EndRem Method GetData:String() Return _data End Method +'#End Region End Type Rem bbdoc: IRC Configuration struct + about: Stores information about a network and connection info for it. EndRem Type IRCClientConfig Field _Network:String Field _Port:Int = 6667 Field _Nick:String Field _Name:String Field _Ident:String +'#Region Get/Set methods + + Rem + bbdoc: Set the server and port + EndRem Method SetServer(network:String, port:Int = 6667) _Network = network _Port = port End Method + Rem + bbdoc: Set the nick + EndRem Method SetNick(nick:String) _Nick = nick End Method + Rem + bbdoc: Set the real name + EndRem Method SetName(name:String) _Name = name End Method + Rem + bbdoc: Set the ident + EndRem Method SetIdent(ident:String) _Ident = ident End Method +'#End Region End Type Rem bbdoc: The main IRC client type EndRem Type IRCClient Global OUTHOOK:Int = AllocHookId() Global INHOOK:Int = AllocHookId() Field _socket:TSocket Field _stream:TSocketStream Field _utf8:TTextStream Field _running:Int = False Rem bbdoc: Connect to a server EndRem Method Connect:Int(config:IRCClientConfig) 'Attempt a TCP connection _socket = TSocket.CreateTCP() _socket.Connect(HostIp(config._Network), config._Port) _stream = CreateSocketStream(_socket) _utf8 = TTextStream.Create(_stream, TTextStream.UTF8) Send("NICK " + config._Nick) Send("USER " + config._Nick + "8 * :" + config._Name) _running = True EndMethod Rem bbdoc: Start the thread EndRem Method BeginThread:TThread() ?threaded Return TThread.Create(IRCClientThread, Self) ? Throw "ERROR: Cannot create an IRC Client thread in non-threaded mode!" End Method + Rem + bbdoc: Send a string to the server + EndRem Method Send(line:String, utf8:Int = True) RunIRCHookThread(IRCEvent.Create(OUTHOOK, Self, line)) If utf8 _utf8.WriteLine(line) Else _stream.WriteLine(line) EndIf End Method + Rem + bbdoc: Execute a client cycle. + EndRem Method Run() While Not _stream.Eof() Local line:String = _stream.ReadLine() RunIRCHookThread(IRCEvent.Create(INHOOK, Self, line)) Wend End Method -'#Region Getter/Setter methods +'#Region Get/Set/Is methods Method IsRunning:Int() Return _running End Method '#End Region EndType +Rem +bbdoc: Run an IRC Event in a new thread. +returns: The new thread +EndRem +Function RunIRCHookThread:TThread(event:IRCEvent) + ?threaded + Return TThread.Create(IRCHookThread, event) + ?Not threaded + IRCHookThread(event) + ? +EndFunction + Function IRCClientThread:Object(data:Object) Local client:IRCClient = IRCClient(data) If Not client Return Null While client.IsRunning() client.Run() Wend End Function -Function RunIRCHookThread:TThread(event:IRCEvent) - ?threaded - Return TThread.Create(IRCHookThread, event) - ?Not threaded - IRCHookThread(event) - ? -EndFunction - Function IRCHookThread:Object(data:Object) Local event:IRCEvent = IRCEvent(data) If (event) Return RunHooks(event._hookid, event) End If End Function
klokan/py2exepp
26787c921a8fad78e3648afd8cacf8f1f8250856
Extra zip step is now moved into setup.py as well. Updated documentation.
diff --git a/README b/README index ce4d7d6..89a911c 100644 --- a/README +++ b/README @@ -1,30 +1,34 @@ Parallel Python and Py2EXE -------------------------- This project is demostration how to bundle a program which is using Parallel Python (parallelpython.com) into the .exe via py2exe. * Requirement (what I have used): Windows XP, Python 2.5 from python.org, py2exe module * Introduction: Parallel Python starts new processes with subprocess.popen() function (on a local machine). The input and output is encoded with "pickle" and transfered via pipe between the processes. Traditionaly the new workers are started as: "python -u ppworker.py" with complete path. Location of python interpreter is detected as sys.executable, location of ppworker.py is derived from __file__. Pickle must be able to read the source code of the function, so .pyc is not enough. A simple proxy function with available source code is enough. Details: http://www.parallelpython.com/component/option,com_smf/Itemid,29/topic,206.0 -Py2exe exectuble is a stripped version of python interpreter, renamed according your script name (so script.exe instead of python.exe). Your script is embeded inside of the .exe file resources and executed during the start of the exe. All dependent python modules are compiled into .pyc/.pyo and zipped into library.zip (which can have different name or can be bundled in the .exe resources as well). +Py2exe exectuble is a stripped version of python interpreter, renamed according your script name (so script.exe instead of python.exe). Your script is embeded inside of the .exe file resources and executed during the start of the exe. All dependent python modules are compiled into .pyc/.pyo and zipped into library.zip (which can have different name or can be bundled in the .exe resources as well). Details: http://www.py2exe.org/index.cgi/FAQ * Usage: python setup.py -zip -u dist/library.zip primes.py cd dist sum_primes.exe -# zip step is necessary to include the source code of function for pickling -# in this moment we must distribute the python.exe binary as well, because py2exe does not correctly implement the "unbuffered" option. -# test for this "unbuffered" alternative is in the "unbuffered" branch of git of this project at github.com +* Notes: + +In the setup.py is an extra "zip" step to include the source code of function necessary for pickle functionality used in parallel python. + +We must distribute the python.exe binary as well, because py2exe does not correctly implement the "unbuffered" option. +Once the "python -u" equivalent is available via py2exe, we have more options: + - Distribute special ppworker.exe (compiled from ppworker.py) + - Implement something like http://docs.python.org/dev/library/multiprocessing.html#multiprocessing.freeze%5Fsupport for pp. diff --git a/setup.py b/setup.py index a8328b0..85b2a67 100755 --- a/setup.py +++ b/setup.py @@ -1,10 +1,15 @@ from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = { 'py2exe': { 'includes': ["pp.ppworker"] } }, console = ["sum_primes.py"], data_files = [ ('',[r'C:\Python25\python.exe']) ], ) + +# We need to add the source code of the function into the library.zip modules +from zipfile import ZipFile +zip = ZipFile('dist/library.zip','a') +zip.write("primes.py")
klokan/py2exepp
83289ed5d097e18ab06dfdb883d8718578682222
Example of py2exe with parallel python (parallelpython.com). Details in the README file.
diff --git a/README b/README new file mode 100644 index 0000000..ce4d7d6 --- /dev/null +++ b/README @@ -0,0 +1,30 @@ +Parallel Python and Py2EXE +-------------------------- + +This project is demostration how to bundle a program which is using Parallel Python (parallelpython.com) into the .exe via py2exe. + +* Requirement (what I have used): + +Windows XP, Python 2.5 from python.org, py2exe module + +* Introduction: + +Parallel Python starts new processes with subprocess.popen() function (on a local machine). The input and output is encoded with "pickle" and transfered via pipe between the processes. Traditionaly the new workers are started as: "python -u ppworker.py" with complete path. +Location of python interpreter is detected as sys.executable, location of ppworker.py is derived from __file__. + +Pickle must be able to read the source code of the function, so .pyc is not enough. A simple proxy function with available source code is enough. +Details: http://www.parallelpython.com/component/option,com_smf/Itemid,29/topic,206.0 + +Py2exe exectuble is a stripped version of python interpreter, renamed according your script name (so script.exe instead of python.exe). Your script is embeded inside of the .exe file resources and executed during the start of the exe. All dependent python modules are compiled into .pyc/.pyo and zipped into library.zip (which can have different name or can be bundled in the .exe resources as well). + +* Usage: + +python setup.py +zip -u dist/library.zip primes.py + +cd dist +sum_primes.exe + +# zip step is necessary to include the source code of function for pickling +# in this moment we must distribute the python.exe binary as well, because py2exe does not correctly implement the "unbuffered" option. +# test for this "unbuffered" alternative is in the "unbuffered" branch of git of this project at github.com diff --git a/pp/__init__.py b/pp/__init__.py index 82c9dab..6a04c7c 100644 --- a/pp/__init__.py +++ b/pp/__init__.py @@ -1,641 +1,644 @@ # Parallel Python Software: http://www.parallelpython.com # Copyright (c) 2005-2009, Vitalii Vanovschi # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. """ Parallel Python Software, Execution Server http://www.parallelpython.com - updates, documentation, examples and support forums """ import os import thread import logging import inspect import sys import types import time import atexit import user import cPickle as pickle import pptransport import ppauto copyright = "Copyright (c) 2005-2009 Vitalii Vanovschi. All rights reserved" version = "1.5.7" # reconnect persistent rworkers in 5 sec _RECONNECT_WAIT_TIME = 5 # we need to have set even in Python 2.3 try: set except NameError: from sets import Set as set _USE_SUBPROCESS = False try: import subprocess _USE_SUBPROCESS = True except ImportError: import popen2 class _Task(object): """Class describing single task (job) """ def __init__(self, server, tid, callback=None, callbackargs=(), group='default'): """Initializes the task""" self.lock = thread.allocate_lock() self.lock.acquire() self.tid = tid self.server = server self.callback = callback self.callbackargs = callbackargs self.group = group self.finished = False self.unpickled = False def finalize(self, sresult): """Finalizes the task. For internal use only""" self.sresult = sresult if self.callback: self.__unpickle() self.lock.release() self.finished = True def __call__(self, raw_result=False): """Retrieves result of the task""" self.wait() if not self.unpickled and not raw_result: self.__unpickle() if raw_result: return self.sresult else: return self.result def wait(self): """Waits for the task""" if not self.finished: self.lock.acquire() self.lock.release() def __unpickle(self): """Unpickles the result of the task""" self.result, sout = pickle.loads(self.sresult) self.unpickled = True if len(sout) > 0: print sout, if self.callback: args = self.callbackargs + (self.result, ) self.callback(*args) class _Worker(object): """Local worker class """ command = "\"" + sys.executable + "\" -u \"" \ + os.path.dirname(os.path.abspath(__file__))\ + os.sep + "ppworker.py\"" + if sys.executable.lower().find('python') == -1: + command = '''python -u -c "import sys; sys.path.append('library.zip'); from pp.ppworker import _WorkerProcess; wp = _WorkerProcess(); wp.run()" ''' + if sys.platform.startswith("win"): # workargound for windows command = "\"" + command + "\"" else: # do not show "Borken pipe message" at exit on unix/linux command += " 2>/dev/null" def __init__(self, restart_on_free, pickle_proto): """Initializes local worker""" self.restart_on_free = restart_on_free self.pickle_proto = pickle_proto self.start() def start(self): """Starts local worker""" if _USE_SUBPROCESS: proc = subprocess.Popen(self.command, stdin=subprocess.PIPE, \ stdout=subprocess.PIPE, stderr=subprocess.PIPE, \ shell=True) self.t = pptransport.CPipeTransport(proc.stdout, proc.stdin) else: self.t = pptransport.CPipeTransport(\ *popen2.popen3(self.command)[:2]) self.pid = int(self.t.receive()) self.t.send(str(self.pickle_proto)) self.is_free = True def stop(self): """Stops local worker""" self.is_free = False self.t.close() def restart(self): """Restarts local worker""" self.stop() self.start() def free(self): """Frees local worker""" if self.restart_on_free: self.restart() else: self.is_free = True class _RWorker(pptransport.CSocketTransport): """Remote worker class """ def __init__(self, host, port, secret, message=None, persistent=True): """Initializes remote worker""" self.persistent = persistent self.host = host self.port = port self.secret = secret self.address = (host, port) self.id = host + ":" + str(port) logging.debug("Creating Rworker id=%s persistent=%s" % (self.id, persistent)) self.connect(message) self.is_free = True def __del__(self): """Closes connection with remote server""" self.close() def connect(self, message=None): """Connects to a remote server""" while True: try: pptransport.SocketTransport.__init__(self) self._connect(self.host, self.port) if not self.authenticate(self.secret): logging.error("Authentication failed for host=%s, port=%s" % (self.host, self.port)) return False if message: self.send(message) self.is_free = True return True except: if not self.persistent: logging.debug("Deleting from queue Rworker %s" % (self.id, )) return False # print sys.excepthook(*sys.exc_info()) logging.debug("Failed to reconnect with " \ "(host=%s, port=%i), will try again in %i s" % (self.host, self.port, _RECONNECT_WAIT_TIME)) time.sleep(_RECONNECT_WAIT_TIME) class _Statistics(object): """Class to hold execution statisitcs for a single node """ def __init__(self, ncpus, rworker=None): """Initializes statistics for a node""" self.ncpus = ncpus self.time = 0.0 self.njobs = 0 self.rworker = rworker class Template(object): """Template class """ def __init__(self, job_server, func, depfuncs=(), modules=(), callback=None, callbackargs=(), group='default', globals=None): """Creates Template instance jobs_server - pp server for submitting jobs func - function to be executed depfuncs - tuple with functions which might be called from 'func' modules - tuple with module names to import callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done callbackargs - additional arguments for callback function group - job group, is used when wait(group) is called to wait for jobs in a given group to finish globals - dictionary from which all modules, functions and classes will be imported, for instance: globals=globals()""" self.job_server = job_server self.func = func self.depfuncs = depfuncs self.modules = modules self.callback = callback self.callbackargs = callbackargs self.group = group self.globals = globals def submit(self, *args): """Submits function with *arg arguments to the execution queue """ return self.job_server.submit(self.func, args, self.depfuncs, self.modules, self.callback, self.callbackargs, self.group, self.globals) class Server(object): """Parallel Python SMP execution server class """ default_port = 60000 default_secret = "epo20pdosl;dksldkmm" def __init__(self, ncpus="autodetect", ppservers=(), secret=None, loglevel=logging.WARNING, logstream=sys.stderr, restart=False, proto=0): """Creates Server instance ncpus - the number of worker processes to start on the local computer, if parameter is omitted it will be set to the number of processors in the system ppservers - list of active parallel python execution servers to connect with secret - passphrase for network connections, if omitted a default passphrase will be used. It's highly recommended to use a custom passphrase for all network connections. loglevel - logging level logstream - log stream destination restart - wheather to restart worker process after each task completion proto - protocol number for pickle module With ncpus = 1 all tasks are executed consequently For the best performance either use the default "autodetect" value or set ncpus to the total number of processors in the system """ if not isinstance(ppservers, tuple): raise TypeError("ppservers argument must be a tuple") self.__initlog(loglevel, logstream) logging.debug("Creating server instance (pp-" + version+")") self.__tid = 0 self.__active_tasks = 0 self.__active_tasks_lock = thread.allocate_lock() self.__queue = [] self.__queue_lock = thread.allocate_lock() self.__workers = [] self.__rworkers = [] self.__rworkers_reserved = [] self.__rworkers_reserved4 = [] self.__sourcesHM = {} self.__sfuncHM = {} self.__waittasks = [] self.__waittasks_lock = thread.allocate_lock() self.__exiting = False self.__accurate_stats = True self.autopp_list = {} self.__active_rworkers_list_lock = thread.allocate_lock() self.__restart_on_free = restart self.__pickle_proto = proto # add local directory and sys.path to PYTHONPATH pythondirs = [os.getcwd()] + sys.path if "PYTHONPATH" in os.environ and os.environ["PYTHONPATH"]: pythondirs += os.environ["PYTHONPATH"].split(os.pathsep) os.environ["PYTHONPATH"] = os.pathsep.join(set(pythondirs)) atexit.register(self.destroy) self.__stats = {"local": _Statistics(0)} self.set_ncpus(ncpus) self.ppservers = [] self.auto_ppservers = [] for ppserver in ppservers: ppserver = ppserver.split(":") host = ppserver[0] if len(ppserver)>1: port = int(ppserver[1]) else: port = Server.default_port if host.find("*") == -1: self.ppservers.append((host, port)) else: if host == "*": host = "*.*.*.*" interface = host.replace("*", "0") broadcast = host.replace("*", "255") self.auto_ppservers.append(((interface, port), (broadcast, port))) self.__stats_lock = thread.allocate_lock() if secret is not None: if not isinstance(secret, types.StringType): raise TypeError("secret must be of a string type") self.secret = str(secret) elif hasattr(user, "pp_secret"): secret = user["pp_secret"] if not isinstance(secret, types.StringType): raise TypeError("secret must be of a string type") self.secret = str(secret) else: self.secret = Server.default_secret self.__connect() self.__creation_time = time.time() logging.info("pp local server started with %d workers" % (self.__ncpus, )) def submit(self, func, args=(), depfuncs=(), modules=(), callback=None, callbackargs=(), group='default', globals=None): """Submits function to the execution queue func - function to be executed args - tuple with arguments of the 'func' depfuncs - tuple with functions which might be called from 'func' modules - tuple with module names to import callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done callbackargs - additional arguments for callback function group - job group, is used when wait(group) is called to wait for jobs in a given group to finish globals - dictionary from which all modules, functions and classes will be imported, for instance: globals=globals() """ # perform some checks for frequent mistakes if self.__exiting: raise RuntimeError("Cannot submit jobs: server"\ " instance has been destroyed") if not isinstance(args, tuple): raise TypeError("args argument must be a tuple") if not isinstance(depfuncs, tuple): raise TypeError("depfuncs argument must be a tuple") if not isinstance(modules, tuple): raise TypeError("modules argument must be a tuple") if not isinstance(callbackargs, tuple): raise TypeError("callbackargs argument must be a tuple") for module in modules: if not isinstance(module, types.StringType): raise TypeError("modules argument must be a list of strings") tid = self.__gentid() if globals: modules += tuple(self.__find_modules("", globals)) modules = tuple(set(modules)) self.__logger.debug("Task %i will autoimport next modules: %s" % (tid, str(modules))) for object1 in globals.values(): if isinstance(object1, types.FunctionType) \ or isinstance(object1, types.ClassType): depfuncs += (object1, ) task = _Task(self, tid, callback, callbackargs, group) self.__waittasks_lock.acquire() self.__waittasks.append(task) self.__waittasks_lock.release() # if the function is a method of a class add self to the arguments list if isinstance(func, types.MethodType) and func.im_self is not None: args = (func.im_self, ) + args # if there is an instance of a user deined class in the arguments add # whole class to dependancies for arg in args: # Checks for both classic or new class instances if isinstance(arg, types.InstanceType) \ or str(type(arg))[:6] == "<class": depfuncs += (arg.__class__, ) # if there is a function in the arguments add this # function to dependancies for arg in args: if isinstance(arg, types.FunctionType): depfuncs += (arg, ) sfunc = self.__dumpsfunc((func, ) + depfuncs, modules) sargs = pickle.dumps(args, self.__pickle_proto) self.__queue_lock.acquire() self.__queue.append((task, sfunc, sargs)) self.__queue_lock.release() self.__logger.debug("Task %i submited, function='%s'" % (tid, func.func_name)) self.__scheduler() return task def wait(self, group=None): """Waits for all jobs in a given group to finish. If group is omitted waits for all jobs to finish """ while True: self.__waittasks_lock.acquire() for task in self.__waittasks: if not group or task.group == group: self.__waittasks_lock.release() task.wait() break else: self.__waittasks_lock.release() break def get_ncpus(self): """Returns the number of local worker processes (ppworkers)""" return self.__ncpus def set_ncpus(self, ncpus="autodetect"): """Sets the number of local worker processes (ppworkers) ncpus - the number of worker processes, if parammeter is omitted it will be set to the number of processors in the system""" if ncpus == "autodetect": ncpus = self.__detect_ncpus() if not isinstance(ncpus, int): raise TypeError("ncpus must have 'int' type") if ncpus < 0: raise ValueError("ncpus must be an integer > 0") if ncpus > len(self.__workers): self.__workers.extend([_Worker(self.__restart_on_free, self.__pickle_proto) for x in\ range(ncpus - len(self.__workers))]) self.__stats["local"].ncpus = ncpus self.__ncpus = ncpus def get_active_nodes(self): """Returns active nodes as a dictionary [keys - nodes, values - ncpus]""" active_nodes = {} for node, stat in self.__stats.items(): if node == "local" or node in self.autopp_list \ and self.autopp_list[node]: active_nodes[node] = stat.ncpus return active_nodes def get_stats(self): """Returns job execution statistics as a dictionary""" for node, stat in self.__stats.items(): if stat.rworker: try: stat.rworker.send("TIME") stat.time = float(stat.rworker.receive()) except: self.__accurate_stats = False stat.time = 0.0 return self.__stats def print_stats(self): """Prints job execution statistics. Useful for benchmarking on clusters""" print "Job execution statistics:" walltime = time.time()-self.__creation_time statistics = self.get_stats().items() totaljobs = 0.0 for ppserver, stat in statistics: totaljobs += stat.njobs print " job count | % of all jobs | job time sum | " \ "time per job | job server" for ppserver, stat in statistics: if stat.njobs: print " %6i | %6.2f | %8.4f | %11.6f | %s" \ % (stat.njobs, 100.0*stat.njobs/totaljobs, stat.time, stat.time/stat.njobs, ppserver, ) print "Time elapsed since server creation", walltime if not self.__accurate_stats: print "WARNING: statistics provided above is not accurate" \ " due to job rescheduling" print # all methods below are for internal use only def insert(self, sfunc, sargs, task=None): """Inserts function into the execution queue. It's intended for internal use only (ppserver.py). """ if not task: tid = self.__gentid() task = _Task(self, tid) self.__queue_lock.acquire() self.__queue.append((task, sfunc, sargs)) self.__queue_lock.release() self.__logger.debug("Task %i inserted" % (task.tid, )) self.__scheduler() return task def connect1(self, host, port, persistent=True): """Conects to a remote ppserver specified by host and port""" try: rworker = _RWorker(host, port, self.secret, "STAT", persistent) ncpus = int(rworker.receive()) hostid = host+":"+str(port) self.__stats[hostid] = _Statistics(ncpus, rworker) for x in range(ncpus): rworker = _RWorker(host, port, self.secret, "EXEC", persistent) self.__update_active_rworkers(rworker.id, 1) # append is atomic - no need to lock self.__rworkers self.__rworkers.append(rworker) #creating reserved rworkers for x in range(ncpus): rworker = _RWorker(host, port, self.secret, "EXEC", persistent) self.__update_active_rworkers(rworker.id, 1) self.__rworkers_reserved.append(rworker) #creating reserved4 rworkers for x in range(ncpus*0): rworker = _RWorker(host, port, self.secret, "EXEC", persistent) # self.__update_active_rworkers(rworker.id, 1) self.__rworkers_reserved4.append(rworker) logging.debug("Connected to ppserver (host=%s, port=%i) \ with %i workers" % (host, port, ncpus)) self.__scheduler() except: pass # sys.excepthook(*sys.exc_info()) def __connect(self): """Connects to all remote ppservers""" for ppserver in self.ppservers: thread.start_new_thread(self.connect1, ppserver) discover = ppauto.Discover(self, True) for ppserver in self.auto_ppservers: thread.start_new_thread(discover.run, ppserver) def __detect_ncpus(self): """Detects the number of effective CPUs in the system""" #for Linux, Unix and MacOS if hasattr(os, "sysconf"): if "SC_NPROCESSORS_ONLN" in os.sysconf_names: #Linux and Unix ncpus = os.sysconf("SC_NPROCESSORS_ONLN") if isinstance(ncpus, int) and ncpus > 0: return ncpus else: #MacOS X return int(os.popen2("sysctl -n hw.ncpu")[1].read()) #for Windows if "NUMBER_OF_PROCESSORS" in os.environ: ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]) if ncpus > 0: return ncpus #return the default value return 1 def __initlog(self, loglevel, logstream): """Initializes logging facility""" log_handler = logging.StreamHandler(logstream) log_handler.setLevel(loglevel) LOG_FORMAT = '%(asctime)s %(levelname)s %(message)s' log_handler.setFormatter(logging.Formatter(LOG_FORMAT)) self.__logger = logging.getLogger('') self.__logger.addHandler(log_handler) self.__logger.setLevel(loglevel) def __dumpsfunc(self, funcs, modules): """Serializes functions and modules""" hashs = hash(funcs + modules) if hashs not in self.__sfuncHM: sources = [self.__get_source(func) for func in funcs] self.__sfuncHM[hashs] = pickle.dumps( (funcs[0].func_name, sources, modules), self.__pickle_proto) return self.__sfuncHM[hashs] def __find_modules(self, prefix, dict): """recursively finds all the modules in dict""" diff --git a/primes.py b/primes.py new file mode 100644 index 0000000..263b6d4 --- /dev/null +++ b/primes.py @@ -0,0 +1,19 @@ +def isprime(n): + """Returns True if n is prime and False otherwise""" + if not isinstance(n, int): + raise TypeError("argument passed to is_prime is not of 'int' type") + if n < 2: + return False + if n == 2: + return True + max = int(math.ceil(math.sqrt(n))) + i = 2 + while i <= max: + if n % i == 0: + return False + i += 1 + return True + +def sum_primes(n): + """Calculates sum of all primes below given integer n""" + return sum([x for x in xrange(2,n) if isprime(x)]) diff --git a/setup.py b/setup.py new file mode 100755 index 0000000..a8328b0 --- /dev/null +++ b/setup.py @@ -0,0 +1,10 @@ +from distutils.core import setup +import py2exe, sys, os + +sys.argv.append('py2exe') + +setup( + options = { 'py2exe': { 'includes': ["pp.ppworker"] } }, + console = ["sum_primes.py"], + data_files = [ ('',[r'C:\Python25\python.exe']) ], +) diff --git a/sum_primes.py b/sum_primes.py index 45f77e2..a296ebd 100755 --- a/sum_primes.py +++ b/sum_primes.py @@ -1,81 +1,66 @@ #!/usr/bin/env python # File: sum_primes.py # Author: Vitalii Vanovschi # Desc: This program demonstrates parallel computations with pp module # It calculates the sum of prime numbers below a given integer in parallel # Parallel Python Software: http://www.parallelpython.com import math import sys import pp -def isprime(n): - """Returns True if n is prime and False otherwise""" - if not isinstance(n, int): - raise TypeError("argument passed to is_prime is not of 'int' type") - if n < 2: - return False - if n == 2: - return True - max = int(math.ceil(math.sqrt(n))) - i = 2 - while i <= max: - if n % i == 0: - return False - i += 1 - return True - - -def sum_primes(n): - """Calculates sum of all primes below given integer n""" - return sum([x for x in xrange(2, n) if isprime(x)]) +# Let's move the functionality to external module - to avoid "could not get source" error for .pyc only +# You have to run: "zip -u dist\library.zip primes.py" +from primes import sum_primes, isprime + +# If you don't want to distribute the source code of your function you can move the functionality to another external module and add it to the list of dependent module names in job_server.submit() - last argument. print """Usage: python sum_primes.py [ncpus] [ncpus] - the number of workers to run in parallel, if omitted it will be set to the number of processors in the system""" # tuple of all parallel python servers to connect with ppservers = () #ppservers = ("10.0.0.1",) if len(sys.argv) > 1: ncpus = int(sys.argv[1]) # Creates jobserver with ncpus workers job_server = pp.Server(ncpus, ppservers=ppservers) else: # Creates jobserver with automatically detected number of workers job_server = pp.Server(ppservers=ppservers) print "Starting pp with", job_server.get_ncpus(), "workers" # Submit a job of calulating sum_primes(100) for execution. # sum_primes - the function # (100,) - tuple with arguments for sum_primes # (isprime,) - tuple with functions on which function sum_primes depends # ("math",) - tuple with module names which must be imported before # sum_primes execution # Execution starts as soon as one of the workers will become available job1 = job_server.submit(sum_primes, (100, ), (isprime, ), ("math", )) # Retrieves the result calculated by job1 # The value of job1() is the same as sum_primes(100) # If the job has not been finished yet, execution will # wait here until result is available result = job1() print "Sum of primes below 100 is", result # The following submits 8 jobs and then retrieves the results inputs = (100000, 100100, 100200, 100300, 100400, 100500, 100600, 100700) jobs = [(input, job_server.submit(sum_primes, (input, ), (isprime, ), ("math", ))) for input in inputs] for input, job in jobs: print "Sum of primes below", input, "is", job() job_server.print_stats() # Parallel Python Software: http://www.parallelpython.com
actridge/carouselFlow
bcd84850d640c598ca849aa182d902d1717abf03
Removed commented out old code and debugging calls, updated project URL
diff --git a/jquery.carouselFlow.js b/jquery.carouselFlow.js index ad06397..7f3f9c6 100644 --- a/jquery.carouselFlow.js +++ b/jquery.carouselFlow.js @@ -1,176 +1,143 @@ /** * CarouselFlow - jQuery plugin to navigate images in a hybrid carousel/coverflow style widget. * @requires jQuery v1.4.2 or above * - * http://actridge.com/projects/carouselflow + * http://github.com/actridge/carouselFlow * * Copyright (c) 2010 Vance Lucas (vancelucas.com) * Released under the MIT license: * http://www.opensource.org/licenses/mit-license.php */ (function($) { $.fn.carouselFlow = function(o) { // Default settings var o = $.extend({ btnPrevSelector: null, btnNextSelector: null, visible: 5, speed: 500, easing: 'linear' }, o || {}); // Return so call is chainable return this.each(function() { var cfDiv = $(this); var cfUl = $('ul', cfDiv); var cfLi = $('li', cfUl); // ============================================== // Make some calculations var cfLiWidth = cfLi.outerWidth(); var cfLiHeight = cfLi.outerHeight(); var eLiWidth = $(':first', cfLi).width(); var eLiHeight = cfLi.height(); // Get center element var cfLiCenter = Math.floor(cfLi.length / 2); var cfUlCenter = Math.ceil(cfUl.width() / 2); // Move the last item before first item, just in case user click prev button $('li:first', cfUl).before($('li:last', cfUl)); // CSS positioning and setup cfDiv.css({'position': 'relative'}); cfUl.css({'position': 'relative', 'overflow': 'hidden', 'list-style-type': 'none', 'width': '100%', 'height': cfLiHeight + 'px'}); cfLi.css({'overflow': 'hidden', 'position': 'absolute', 'display': 'block'}); // Main object with functions var cf = { // Visible elements on either side of center element visibleLis: function(center) { var center = center || cfLiCenter; return $('li', cfUl).slice(Math.floor(o.visible-center)).slice(0, center+1); }, cloneLi: function(dir) { if(dir == 'next') { // Clone the first item and put it as last item $('li:last', cfUl).after($('li:first', cfUl)); } else if(dir == 'prev') { // Clone the last item and put it as first item $('li:first', cfUl).before($('li:last', cfUl)); } }, // Slide carousel to index position as center slideTo: function(index, animate) { var index = index || cfLiCenter; var animate = animate || true; var dir = false; // Determine direction if(index < cfLiCenter) { dir = 'prev'; } else if(index > cfLiCenter) { dir = 'next'; } else { //var dir = false; } if(dir !== false) { // Clone list item cf.cloneLi(dir); } // Animation sequence // ============================================ $('li', cfUl).each(function(i, value) { //var eLiWidth, eLiHeight; // Size ratio == 100% for center or -{o.stepping}% for each 'step' away from center var eLiStep = cfLiCenter - i; var eLiStepAbs = Math.abs(eLiStep); var eLiSizeRatio = (i == cfLiCenter) ? 100 : (100 - (eLiStep * o.stepping)); var eLiSizeRatioAbs = (i == cfLiCenter) ? 100 : (100 - (eLiStepAbs * o.stepping)); var eLi = $(this); - /* - // Width - ensure original is stored - if(!eLi.data('oWidth')) { - eLiWidth = eLi.data('oWidth', eLi.width()); - } - eLiWidth = eLi.data('oWidth'); - // Height - ensure original is stored - if(!eLi.data('oHeight')) { - eLiHeight = eLi.data('oHeight', eLi.height()); - } - eLiHeight = eLi.data('oHeight'); - */ - // CSS property setup var eLiCss = { 'width': parseInt(eLiWidth*(eLiSizeRatioAbs/100), 10)+'px', 'height': parseInt(eLiHeight*(eLiSizeRatioAbs/100), 10)+'px', 'top': parseInt((eLiHeight - eLiHeight*(eLiSizeRatioAbs/100))/2, 10)+'px' }; // Calculate left position (needs to be after final width is calculated) eLiCss.left = parseInt(cfUlCenter + cfUlCenter*((100 - eLiSizeRatio)/100) - (eLiCss.width.replace('px', '')/2), 10)+'px'; // Set CSS properties on carousel items // Only IMG supported for now // @todo Add support for any content eLi.css({'zIndex': Math.floor(eLiSizeRatioAbs / 10)}) if(animate) { eLi.find('img').andSelf().animate(eLiCss, o.speed, o.easing); } else { eLi.find('img').andSelf().css(eLiCss); } - - /* - console.log('Step['+i+']: ' + eLiStep + ' -- Ratio: ' + eLiSizeRatio + - ' -- Width: ' + eLiCss.width + - ' -- Height: ' + eLiCss.height + - ' -- Left: ' + eLiCss.left + - ' -- Top: ' + eLiCss.top + - ' -- zIndex: ' + Math.floor(eLiSizeRatioAbs / 10) - ); - //*/ }); /* console.log('Center: ' + cfUlCenter); console.log('Min. Width: ' + Array.min(elsWidths)); */ // ============================================ } }; // START the process cf.slideTo(cfLiCenter, false); // PREVIOUS $(o.btnPrevSelector).click(function() { cf.slideTo(cfLiCenter-1); return false; }); // NEXT $(o.btnNextSelector).click(function() { cf.slideTo(cfLiCenter+1); return false; }); - // ============================================== }); }; -})(jQuery); - -// Extending the 'Array' type with prototype methods -// @link http://ejohn.org/blog/fast-javascript-maxmin/ -Array.max = function( array ){ - return Math.max.apply( Math, array ); -}; -Array.min = function( array ){ - return Math.min.apply( Math, array ); -}; \ No newline at end of file +})(jQuery); \ No newline at end of file
actridge/carouselFlow
49048c67ec43ce2edff734d00cd0810db6093125
Initial fully working version - No longer based on any other carousel base - fully custom.
diff --git a/jquery.carouselFlow.js b/jquery.carouselFlow.js index b414ced..ad06397 100644 --- a/jquery.carouselFlow.js +++ b/jquery.carouselFlow.js @@ -1,192 +1,176 @@ /** * CarouselFlow - jQuery plugin to navigate images in a hybrid carousel/coverflow style widget. - * @requires jQuery v1.3.2 or above + * @requires jQuery v1.4.2 or above * - * http://actridge.com/projects/carouselFlow + * http://actridge.com/projects/carouselflow * * Copyright (c) 2010 Vance Lucas (vancelucas.com) * Released under the MIT license: * http://www.opensource.org/licenses/mit-license.php */ -/** - * Based on the great work by: - * - * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget. - * @requires jQuery v1.2 or above - * - * http://gmarwaha.com/jquery/jcarousellite/ - * - * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com) - * Dual licensed under the MIT and GPL licenses: - * http://www.opensource.org/licenses/mit-license.php - * http://www.gnu.org/licenses/gpl.html - */ (function($) { -$.fn.carouselFlow = function(o) { - var o = $.extend({ - btnPrev: null, - btnNext: null, - btnGo: null, - mouseWheel: false, - auto: null, - - speed: 200, - easing: null, - - vertical: false, - circular: true, - visible: 5, - start: 0, - scroll: 1, - - width: 'auto', - - beforeStart: null, - afterEnd: null - }, o || {}); - - return this.each(function() { // Returns the element collection. Chainable. - - var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width"; - var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible; - - if(o.circular) { - ul.prepend(tLi.slice(tl-v-1+1).clone()) - .append(tLi.slice(0,v).clone()); - o.start += v; - } - - var li = $("li", ul), itemLength = li.size(), curr = o.start; - div.css("visibility", "visible"); - - li.css({overflow: "hidden", float: o.vertical ? "none" : "left"}); - ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"}); - div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"}); - - var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation - var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items) - if(o.width == 'auto') { - var divSize = liSize * v; // size of entire div(total length for just the visible items) - } else { - var divSize = o.width; - } - - li.css({width: li.width(), height: li.height()}); - ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); - - div.css(sizeCss, divSize+"px"); // Width of the DIV. length of visible images - - if(o.btnPrev) - $(o.btnPrev).click(function() { - return go(curr-o.scroll); - }); - - if(o.btnNext) - $(o.btnNext).click(function() { - return go(curr+o.scroll); - }); - - if(o.btnGo) - $.each(o.btnGo, function(i, val) { - $(val).click(function() { - return go(o.circular ? o.visible+i : i); - }); - }); - - if(o.mouseWheel && div.mousewheel) - div.mousewheel(function(e, d) { - return d>0 ? go(curr-o.scroll) : go(curr+o.scroll); - }); - - if(o.auto) - setInterval(function() { - go(curr+o.scroll); - }, o.auto+o.speed); - - function vis() { - return li.slice(curr).slice(0,v); - }; - - function go(to) { - if(!running) { - - if(o.beforeStart) { - o.beforeStart.call(this, vis()); - } - - //* - console.log(li); - // Animate sizes - center one 100%, left and right flank and reduce sizes in 10% steps (by default) - itemSizeEach = v - li.each(function() { - var itemSizeMulti = tl-v; - $(this).animate({ - 'width': itemSizeMulti*100+'px', - 'height': itemSizeMulti*100+'px' - }, o.speed, o.easing, function() {}); - }); - //*/ - - if(o.circular) { // If circular we are in first or last, then goto the other end - if(to<=o.start-v-1) { // If first, then goto last - ul.css(animCss, -((itemLength-(v*2))*liSize)+"px"); - // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements. - curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll; - } else if(to>=itemLength-v+1) { // If last, then goto first - ul.css(animCss, -( (v) * liSize ) + "px" ); - // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements. - curr = to==itemLength-v+1 ? v+1 : v+o.scroll; - } else curr = to; - } else { // If non-circular and to points to first or last, we just return. - if(to<0 || to>itemLength-v) return; - else curr = to; - } // If neither overrides it, the curr will still be "to" and we can proceed. - - running = true; - - ul.animate( - animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing, - function() { - if(o.afterEnd) - o.afterEnd.call(this, vis()); - running = false; - } - ); - // Disable buttons when the carousel reaches the last/first, and enable when not - if(!o.circular) { - $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); - $( (curr-o.scroll<0 && o.btnPrev) - || - (curr+o.scroll > itemLength-v && o.btnNext) - || - [] - ).addClass("disabled"); - } + $.fn.carouselFlow = function(o) { + // Default settings + var o = $.extend({ + btnPrevSelector: null, + btnNextSelector: null, + + visible: 5, + speed: 500, + easing: 'linear' + }, o || {}); + + // Return so call is chainable + return this.each(function() { + var cfDiv = $(this); + var cfUl = $('ul', cfDiv); + var cfLi = $('li', cfUl); + + // ============================================== + // Make some calculations + var cfLiWidth = cfLi.outerWidth(); + var cfLiHeight = cfLi.outerHeight(); + var eLiWidth = $(':first', cfLi).width(); + var eLiHeight = cfLi.height(); + // Get center element + var cfLiCenter = Math.floor(cfLi.length / 2); + var cfUlCenter = Math.ceil(cfUl.width() / 2); + + // Move the last item before first item, just in case user click prev button + $('li:first', cfUl).before($('li:last', cfUl)); + + // CSS positioning and setup + cfDiv.css({'position': 'relative'}); + cfUl.css({'position': 'relative', 'overflow': 'hidden', 'list-style-type': 'none', + 'width': '100%', + 'height': cfLiHeight + 'px'}); + cfLi.css({'overflow': 'hidden', 'position': 'absolute', 'display': 'block'}); + + // Main object with functions + var cf = { + // Visible elements on either side of center element + visibleLis: function(center) { + var center = center || cfLiCenter; + return $('li', cfUl).slice(Math.floor(o.visible-center)).slice(0, center+1); + }, - /* - alert( - 'Total: ' + tl + '\n' + - 'Current: ' + curr + '\n' + - 'Start: ' + o.start + '\n' + - 'Visible: ' + v + '\n' + - 'Length: ' + itemLength + '\n' + - 'DIV Size: ' + divSize + '\n' - ); - */ - } - return false; - }; - }); -}; - -function css(el, prop) { - return parseInt($.css(el[0], prop)) || 0; -}; -function width(el) { - return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); -}; -function height(el) { - return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); + cloneLi: function(dir) { + if(dir == 'next') { + // Clone the first item and put it as last item + $('li:last', cfUl).after($('li:first', cfUl)); + } else if(dir == 'prev') { + // Clone the last item and put it as first item + $('li:first', cfUl).before($('li:last', cfUl)); + } + }, + + // Slide carousel to index position as center + slideTo: function(index, animate) { + var index = index || cfLiCenter; + var animate = animate || true; + var dir = false; + + // Determine direction + if(index < cfLiCenter) { + dir = 'prev'; + } else if(index > cfLiCenter) { + dir = 'next'; + } else { + //var dir = false; + } + + if(dir !== false) { + // Clone list item + cf.cloneLi(dir); + } + + // Animation sequence + // ============================================ + $('li', cfUl).each(function(i, value) { + //var eLiWidth, eLiHeight; + + // Size ratio == 100% for center or -{o.stepping}% for each 'step' away from center + var eLiStep = cfLiCenter - i; + var eLiStepAbs = Math.abs(eLiStep); + var eLiSizeRatio = (i == cfLiCenter) ? 100 : (100 - (eLiStep * o.stepping)); + var eLiSizeRatioAbs = (i == cfLiCenter) ? 100 : (100 - (eLiStepAbs * o.stepping)); + var eLi = $(this); + + /* + // Width - ensure original is stored + if(!eLi.data('oWidth')) { + eLiWidth = eLi.data('oWidth', eLi.width()); + } + eLiWidth = eLi.data('oWidth'); + // Height - ensure original is stored + if(!eLi.data('oHeight')) { + eLiHeight = eLi.data('oHeight', eLi.height()); + } + eLiHeight = eLi.data('oHeight'); + */ + + // CSS property setup + var eLiCss = { + 'width': parseInt(eLiWidth*(eLiSizeRatioAbs/100), 10)+'px', + 'height': parseInt(eLiHeight*(eLiSizeRatioAbs/100), 10)+'px', + 'top': parseInt((eLiHeight - eLiHeight*(eLiSizeRatioAbs/100))/2, 10)+'px' + }; + + // Calculate left position (needs to be after final width is calculated) + eLiCss.left = parseInt(cfUlCenter + cfUlCenter*((100 - eLiSizeRatio)/100) - (eLiCss.width.replace('px', '')/2), 10)+'px'; + + // Set CSS properties on carousel items + // Only IMG supported for now + // @todo Add support for any content + eLi.css({'zIndex': Math.floor(eLiSizeRatioAbs / 10)}) + if(animate) { + eLi.find('img').andSelf().animate(eLiCss, o.speed, o.easing); + } else { + eLi.find('img').andSelf().css(eLiCss); + } + + /* + console.log('Step['+i+']: ' + eLiStep + ' -- Ratio: ' + eLiSizeRatio + + ' -- Width: ' + eLiCss.width + + ' -- Height: ' + eLiCss.height + + ' -- Left: ' + eLiCss.left + + ' -- Top: ' + eLiCss.top + + ' -- zIndex: ' + Math.floor(eLiSizeRatioAbs / 10) + ); + //*/ + }); + /* + console.log('Center: ' + cfUlCenter); + console.log('Min. Width: ' + Array.min(elsWidths)); + */ + // ============================================ + } + }; + + // START the process + cf.slideTo(cfLiCenter, false); + + // PREVIOUS + $(o.btnPrevSelector).click(function() { + cf.slideTo(cfLiCenter-1); + return false; + }); + + // NEXT + $(o.btnNextSelector).click(function() { + cf.slideTo(cfLiCenter+1); + return false; + }); + // ============================================== + }); + }; +})(jQuery); + +// Extending the 'Array' type with prototype methods +// @link http://ejohn.org/blog/fast-javascript-maxmin/ +Array.max = function( array ){ + return Math.max.apply( Math, array ); }; - -})(jQuery); \ No newline at end of file +Array.min = function( array ){ + return Math.min.apply( Math, array ); +}; \ No newline at end of file
actridge/carouselFlow
17399b17a51af96402ee96bd6f85df5f0f2049a9
Initial working file
diff --git a/jquery.carouselFlow.js b/jquery.carouselFlow.js new file mode 100644 index 0000000..b414ced --- /dev/null +++ b/jquery.carouselFlow.js @@ -0,0 +1,192 @@ +/** + * CarouselFlow - jQuery plugin to navigate images in a hybrid carousel/coverflow style widget. + * @requires jQuery v1.3.2 or above + * + * http://actridge.com/projects/carouselFlow + * + * Copyright (c) 2010 Vance Lucas (vancelucas.com) + * Released under the MIT license: + * http://www.opensource.org/licenses/mit-license.php + */ +/** + * Based on the great work by: + * + * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget. + * @requires jQuery v1.2 or above + * + * http://gmarwaha.com/jquery/jcarousellite/ + * + * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com) + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + */ +(function($) { +$.fn.carouselFlow = function(o) { + var o = $.extend({ + btnPrev: null, + btnNext: null, + btnGo: null, + mouseWheel: false, + auto: null, + + speed: 200, + easing: null, + + vertical: false, + circular: true, + visible: 5, + start: 0, + scroll: 1, + + width: 'auto', + + beforeStart: null, + afterEnd: null + }, o || {}); + + return this.each(function() { // Returns the element collection. Chainable. + + var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width"; + var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible; + + if(o.circular) { + ul.prepend(tLi.slice(tl-v-1+1).clone()) + .append(tLi.slice(0,v).clone()); + o.start += v; + } + + var li = $("li", ul), itemLength = li.size(), curr = o.start; + div.css("visibility", "visible"); + + li.css({overflow: "hidden", float: o.vertical ? "none" : "left"}); + ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"}); + div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"}); + + var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation + var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items) + if(o.width == 'auto') { + var divSize = liSize * v; // size of entire div(total length for just the visible items) + } else { + var divSize = o.width; + } + + li.css({width: li.width(), height: li.height()}); + ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); + + div.css(sizeCss, divSize+"px"); // Width of the DIV. length of visible images + + if(o.btnPrev) + $(o.btnPrev).click(function() { + return go(curr-o.scroll); + }); + + if(o.btnNext) + $(o.btnNext).click(function() { + return go(curr+o.scroll); + }); + + if(o.btnGo) + $.each(o.btnGo, function(i, val) { + $(val).click(function() { + return go(o.circular ? o.visible+i : i); + }); + }); + + if(o.mouseWheel && div.mousewheel) + div.mousewheel(function(e, d) { + return d>0 ? go(curr-o.scroll) : go(curr+o.scroll); + }); + + if(o.auto) + setInterval(function() { + go(curr+o.scroll); + }, o.auto+o.speed); + + function vis() { + return li.slice(curr).slice(0,v); + }; + + function go(to) { + if(!running) { + + if(o.beforeStart) { + o.beforeStart.call(this, vis()); + } + + //* + console.log(li); + // Animate sizes - center one 100%, left and right flank and reduce sizes in 10% steps (by default) + itemSizeEach = v + li.each(function() { + var itemSizeMulti = tl-v; + $(this).animate({ + 'width': itemSizeMulti*100+'px', + 'height': itemSizeMulti*100+'px' + }, o.speed, o.easing, function() {}); + }); + //*/ + + if(o.circular) { // If circular we are in first or last, then goto the other end + if(to<=o.start-v-1) { // If first, then goto last + ul.css(animCss, -((itemLength-(v*2))*liSize)+"px"); + // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements. + curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll; + } else if(to>=itemLength-v+1) { // If last, then goto first + ul.css(animCss, -( (v) * liSize ) + "px" ); + // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements. + curr = to==itemLength-v+1 ? v+1 : v+o.scroll; + } else curr = to; + } else { // If non-circular and to points to first or last, we just return. + if(to<0 || to>itemLength-v) return; + else curr = to; + } // If neither overrides it, the curr will still be "to" and we can proceed. + + running = true; + + ul.animate( + animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing, + function() { + if(o.afterEnd) + o.afterEnd.call(this, vis()); + running = false; + } + ); + // Disable buttons when the carousel reaches the last/first, and enable when not + if(!o.circular) { + $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); + $( (curr-o.scroll<0 && o.btnPrev) + || + (curr+o.scroll > itemLength-v && o.btnNext) + || + [] + ).addClass("disabled"); + } + + /* + alert( + 'Total: ' + tl + '\n' + + 'Current: ' + curr + '\n' + + 'Start: ' + o.start + '\n' + + 'Visible: ' + v + '\n' + + 'Length: ' + itemLength + '\n' + + 'DIV Size: ' + divSize + '\n' + ); + */ + } + return false; + }; + }); +}; + +function css(el, prop) { + return parseInt($.css(el[0], prop)) || 0; +}; +function width(el) { + return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); +}; +function height(el) { + return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); +}; + +})(jQuery); \ No newline at end of file
rickatnight11/aeon-embiggen
a475ebb4b7c7acef8dfb289d20f6a63186b63c2d
Fixed Ubuntu bug
diff --git a/aeon_embiggen.pl b/aeon_embiggen.pl index 943cecf..524c25e 100644 --- a/aeon_embiggen.pl +++ b/aeon_embiggen.pl @@ -1,188 +1,193 @@ use strict; use File::Copy; my $valid_extensions = "iso img dat bin cue vob dvb m2t mts evo mp4 avi asf asx wmv wma mov flv swf nut avs nsv ram ogg ogm ogv mkv viv pva mpg"; my $path = $ARGV[0]; if (!defined $path) { print STDERR "\nNo directory passed in.\nPlease supply a directory containing the MOVIES\nyou want to copy thumbnails for: "; $path = <STDIN>; } chomp $path; chdir($path) or die "I wasn't unable to chdir to $path"; if ($^O eq "MSWin32") { $path =~ s/\\/\\\\/g; # Windows: Add a double slash for every single slash } $path =~ s/^"|"$//g; # Strip quotes. you dirty girl. my @files = findThumbs($path, 0); if ($#files < 0) { print STDERR "\nI didn't find any files to copy. Sorry."; exit -1; } print STDOUT "\n\n\n-----------Starting Copy Process-----------"; foreach (@files) { $_ =~ s/(^\s+)|(\s+$)//g; # Remove whitespace my $tbn = $_; $tbn =~ s/\.\w+$/\.tbn/; my $big = $_; $big .= '-big.png'; if (-e $tbn) { print "\nCopying $tbn to $big..."; copy($tbn, $big) or print STDERR "\nUnable to copy $tbn to $big"; } else { print STDERR "\nUnable to locate $tbn: Not copying."; } } print "\nThe magic that is perl has completed. Review the changes, and I hope this didn't destroy anything.\n"; sub findThumbs { my $path = shift or die "You didn't supply enough arguments!"; my $numTabs = shift; my @temps; opendir(DIR, $path) or die "Cannot do! The path was $path"; foreach my $name (sort readdir(DIR)) { my $formatting = ""; if ($name eq "." || $name eq "..") { next; } else { $formatting .= "\n"; for (my $lcv = 0; $lcv <= $numTabs; $lcv++) { $formatting .= "\t"; } } - - my $filename = $path . "\\" . $name; + + my $filename; + if ($^O eq "MSWin32") { + $filename = $path . "\\" . $name; + } else { + $filename = $path . "/" . $name; + } if (-d $filename) { print "$formatting" . "$name is a directory - Recursing."; push @temps, findThumbs($filename, $numTabs+1); } elsif (-f $filename) { my $temp = $filename; # Preserve the original - $temp =~ s/(^\s+)|(\s+$)//g; # Remove whitespace + $temp =~ s/(^\s+)|(\s+$)//g; # Remove whitespace my $extension = $temp; # The file extension if ($extension =~ m/\.(\w+$)/) { $extension = $1; } else { print "$formatting" . "Unable to parse an extension for $temp... That's interesting."; next; } if ($valid_extensions =~ m/$extension/) { # If the extension was one of those in the big long list #We got us a movie file here, boss! my $tbn = $temp; $tbn =~ s/\.\w+$/\.tbn/; my $already_done = 0; foreach (@temps) { if ($tbn eq $_) { $already_done = 1; last; } } if (-e $tbn && !$already_done) { push @temps, $filename; print "$formatting" . "To be copied: $tbn"; } else { print "$formatting" . "Unable to locate $tbn: Not copying."; } } } else { print "$formatting" . "I have no idea what $name is..."; } } return @temps; closedir(DIR); } \ No newline at end of file
rickatnight11/aeon-embiggen
8b91db8dcb0569f8817c9169af074d963d62d8cc
Completely automated the script.
diff --git a/aeon_embiggen.pl b/aeon_embiggen.pl index 1cd8a33..943cecf 100644 --- a/aeon_embiggen.pl +++ b/aeon_embiggen.pl @@ -1,27 +1,188 @@ use strict; + use File::Copy; -my $instruction_file = $ARGV[0]; -if (!defined $instruction_file) { - print STDERR "\nNo text file passed in.\nPlease supply a text file containing the MOVIES you want to copy thumbnails for: "; - $instruction_file = <STDIN>; +my $valid_extensions = "iso img dat bin cue vob dvb m2t mts evo mp4 avi asf asx wmv wma mov flv swf nut avs nsv ram ogg ogm ogv mkv viv pva mpg"; + +my $path = $ARGV[0]; + +if (!defined $path) { + + print STDERR "\nNo directory passed in.\nPlease supply a directory containing the MOVIES\nyou want to copy thumbnails for: "; + + $path = <STDIN>; + +} + +chomp $path; + +chdir($path) or die "I wasn't unable to chdir to $path"; + +if ($^O eq "MSWin32") { + + $path =~ s/\\/\\\\/g; # Windows: Add a double slash for every single slash + } -open (INSTRUCT, $instruction_file) or die "I couldn't open the instruction file - pass it in as an argument."; -my @files = <INSTRUCT>; +$path =~ s/^"|"$//g; # Strip quotes. you dirty girl. + +my @files = findThumbs($path, 0); + +if ($#files < 0) + +{ + + print STDERR "\nI didn't find any files to copy. Sorry."; + + exit -1; + +} + +print STDOUT "\n\n\n-----------Starting Copy Process-----------"; + foreach (@files) + { - $_ =~ s/(^\s+)|(\s+$)//g; # Remove whitespace - my $tbn = $_; - $tbn =~ s/\.\w+$/\.tbn/; - my $big = $_; - $big .= '-big.png'; - - if (-e $tbn) { - print "\nCopying $tbn to $big..."; - copy($tbn, $big) or print STDERR "\nUnable to copy $tbn to $big"; - } else { - print STDERR "\nUnable to locate $tbn: Not copying."; - } + + $_ =~ s/(^\s+)|(\s+$)//g; # Remove whitespace + + my $tbn = $_; + + $tbn =~ s/\.\w+$/\.tbn/; + + my $big = $_; + + $big .= '-big.png'; + + + + if (-e $tbn) { + + print "\nCopying $tbn to $big..."; + + copy($tbn, $big) or print STDERR "\nUnable to copy $tbn to $big"; + + } else { + + print STDERR "\nUnable to locate $tbn: Not copying."; + + } + } -print "\nThe magic that is perl has completed. Review the changes, and I hope this didn't destroy anything.\n"; \ No newline at end of file + +print "\nThe magic that is perl has completed. Review the changes, and I hope this didn't destroy anything.\n"; + + +sub findThumbs + +{ + + my $path = shift or die "You didn't supply enough arguments!"; + + my $numTabs = shift; + + my @temps; + + opendir(DIR, $path) or die "Cannot do! The path was $path"; + + foreach my $name (sort readdir(DIR)) + + { + + my $formatting = ""; + + if ($name eq "." || $name eq "..") + + { next; } + + else { + + $formatting .= "\n"; + + for (my $lcv = 0; $lcv <= $numTabs; $lcv++) { + + $formatting .= "\t"; + + } + + } + + my $filename = $path . "\\" . $name; + + if (-d $filename) { + + print "$formatting" . "$name is a directory - Recursing."; + + push @temps, findThumbs($filename, $numTabs+1); + + } elsif (-f $filename) { + + my $temp = $filename; # Preserve the original + + $temp =~ s/(^\s+)|(\s+$)//g; # Remove whitespace + + my $extension = $temp; # The file extension + + if ($extension =~ m/\.(\w+$)/) { + + $extension = $1; + + } else { + + print "$formatting" . "Unable to parse an extension for $temp... That's interesting."; + + next; + + } + + if ($valid_extensions =~ m/$extension/) { # If the extension was one of those in the big long list + + #We got us a movie file here, boss! + + my $tbn = $temp; + + $tbn =~ s/\.\w+$/\.tbn/; + + my $already_done = 0; + + foreach (@temps) { + + if ($tbn eq $_) + + { + + $already_done = 1; + + last; + + } + + } + + if (-e $tbn && !$already_done) { + + push @temps, $filename; + + print "$formatting" . "To be copied: $tbn"; + + } else { + + print "$formatting" . "Unable to locate $tbn: Not copying."; + + } + + } + + } else { + + print "$formatting" . "I have no idea what $name is..."; + + } + + } + + return @temps; + + closedir(DIR); + +} \ No newline at end of file
rickatnight11/aeon-embiggen
f4bc004e632954ad038f3cbec7f6f66323f9e2ca
Initial aeon_embiggen_0.9 import.
diff --git a/aeon_embiggen.pl b/aeon_embiggen.pl new file mode 100644 index 0000000..1cd8a33 --- /dev/null +++ b/aeon_embiggen.pl @@ -0,0 +1,27 @@ +use strict; +use File::Copy; + +my $instruction_file = $ARGV[0]; +if (!defined $instruction_file) { + print STDERR "\nNo text file passed in.\nPlease supply a text file containing the MOVIES you want to copy thumbnails for: "; + $instruction_file = <STDIN>; +} + +open (INSTRUCT, $instruction_file) or die "I couldn't open the instruction file - pass it in as an argument."; +my @files = <INSTRUCT>; +foreach (@files) +{ + $_ =~ s/(^\s+)|(\s+$)//g; # Remove whitespace + my $tbn = $_; + $tbn =~ s/\.\w+$/\.tbn/; + my $big = $_; + $big .= '-big.png'; + + if (-e $tbn) { + print "\nCopying $tbn to $big..."; + copy($tbn, $big) or print STDERR "\nUnable to copy $tbn to $big"; + } else { + print STDERR "\nUnable to locate $tbn: Not copying."; + } +} +print "\nThe magic that is perl has completed. Review the changes, and I hope this didn't destroy anything.\n"; \ No newline at end of file
lllkoballl/testapp
59f79fb938b503cbca308b9efd35c22823c5e7d2
ぶらんち
diff --git a/Hoge.as b/Hoge.as index 58df292..2c43c86 100644 --- a/Hoge.as +++ b/Hoge.as @@ -1,14 +1,15 @@ package { import flash.display.*; public class Hoge extends Sprite { public function Hoge() { trace("hoge hoge"); trace("mmm"); + trace("っっっっっっっらんちー"); } } }
lllkoballl/testapp
52a2a7d396835da8d26b4a15ff1be5c3daea2b14
modified: Hoge.as
diff --git a/Hoge.as b/Hoge.as index e8db3d8..58df292 100644 --- a/Hoge.as +++ b/Hoge.as @@ -1,13 +1,14 @@ package { import flash.display.*; public class Hoge extends Sprite { public function Hoge() { trace("hoge hoge"); + trace("mmm"); } } }
lllkoballl/testapp
2073983ea5e83ce3de7f35b74dac217ffb95b704
日本語
diff --git a/Hoge.as b/Hoge.as index 51c4029..e8db3d8 100644 --- a/Hoge.as +++ b/Hoge.as @@ -1,13 +1,13 @@ -pakcuge +package { import flash.display.*; public class Hoge extends Sprite { public function Hoge() { trace("hoge hoge"); } } }
lllkoballl/testapp
b0310545ede30aec37afcd8fd4d2d30fd8b08a3b
add Hoge.as
diff --git a/Hoge.as b/Hoge.as new file mode 100644 index 0000000..1de8d1a --- /dev/null +++ b/Hoge.as @@ -0,0 +1,12 @@ +pakcuge +{ + import flash.display.*; + + public class Hoge extends Sprite + { + public function Hoge() + { + } + } +} +
djberg96/sys-uptime
3fe2a3bbceafb6c3b804f061685e6a1fc909cc58
Add 3.4 to workflow.
diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index 955ce24..6a6a3f4 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -1,52 +1,52 @@ name: Ruby on: push: branches: [ main ] paths-ignore: - '**/*.md' pull_request: branches: [ main ] paths-ignore: - '**/*.md' workflow_dispatch: jobs: test: strategy: matrix: - ruby-version: ['2.7', '3.0', '3.1', '3.2', '3.3', 'jruby', 'truffleruby'] + ruby-version: ['2.7', '3.0', '3.1', '3.2', '3.3', '3.4', 'jruby', 'truffleruby'] platform: [ubuntu-latest, macos-latest, windows-latest] exclude: - ruby-version: truffleruby platform: windows-latest - ruby-version: jruby platform: windows-latest - ruby-version: 3.0 platform: windows-latest runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v4 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true - name: Run tests run: bundle exec rake freebsd: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Test in FreeBSD id: test uses: vmactions/freebsd-vm@v1 with: usesh: true prepare: | pkg install -y ruby devel/ruby-gems run: | gem install bundler --no-document bundle install --quiet bundle exec rspec
djberg96/sys-uptime
08ca87b4fd6b700e8268322ce83517e1ea9f28fa
Add funding_uri.
diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 952fb70..afc7ff2 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,42 +1,43 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' spec.version = '0.7.6' spec.author = 'Daniel J. Berger' spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'spec/sys_uptime_spec.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] if File::ALT_SEPARATOR spec.platform = Gem::Platform.new(['universal', 'mingw32']) else spec.add_dependency('ffi', '~> 1.1') end spec.add_development_dependency('rake') spec.add_development_dependency('rspec', '~> 3.9') spec.add_development_dependency('rubocop') spec.add_development_dependency('rubocop-rspec') spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/main/CHANGES.md', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'rubygems_mfa_required' => 'true', - 'github_repo' => 'https://github.com/djberg96/sys-uptime' + 'github_repo' => 'https://github.com/djberg96/sys-uptime', + 'funding_uri' => 'https://github.com/sponsors/djberg96' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
820e780eb77e7f2632990e47ccdf6e1765d4e719
Bump ruby workflow to v4.
diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index e3ede88..955ce24 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -1,52 +1,52 @@ name: Ruby on: push: branches: [ main ] paths-ignore: - '**/*.md' pull_request: branches: [ main ] paths-ignore: - '**/*.md' workflow_dispatch: jobs: test: strategy: matrix: ruby-version: ['2.7', '3.0', '3.1', '3.2', '3.3', 'jruby', 'truffleruby'] platform: [ubuntu-latest, macos-latest, windows-latest] exclude: - ruby-version: truffleruby platform: windows-latest - ruby-version: jruby platform: windows-latest - ruby-version: 3.0 platform: windows-latest runs-on: ${{ matrix.platform }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true - name: Run tests run: bundle exec rake freebsd: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Test in FreeBSD id: test uses: vmactions/freebsd-vm@v1 with: usesh: true prepare: | pkg install -y ruby devel/ruby-gems run: | gem install bundler --no-document bundle install --quiet bundle exec rspec
djberg96/sys-uptime
2497d372393dfd8a42dffc7915950b2d464f8f16
Add FreeBSD to workflow.
diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index 3bab29a..e3ede88 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -1,36 +1,52 @@ name: Ruby on: push: branches: [ main ] paths-ignore: - '**/*.md' pull_request: branches: [ main ] paths-ignore: - '**/*.md' workflow_dispatch: jobs: test: strategy: matrix: - ruby-version: ['2.6', '2.7', '3.0', '3.1', '3.2', '3.3', 'jruby', 'truffleruby'] + ruby-version: ['2.7', '3.0', '3.1', '3.2', '3.3', 'jruby', 'truffleruby'] platform: [ubuntu-latest, macos-latest, windows-latest] exclude: - ruby-version: truffleruby platform: windows-latest - ruby-version: jruby platform: windows-latest - ruby-version: 3.0 platform: windows-latest runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true - name: Run tests run: bundle exec rake + freebsd: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Test in FreeBSD + id: test + uses: vmactions/freebsd-vm@v1 + with: + usesh: true + prepare: | + pkg install -y ruby devel/ruby-gems + + run: | + gem install bundler --no-document + bundle install --quiet + bundle exec rspec
djberg96/sys-uptime
506d0907990e52f0959be768c87d5b3f697c73d9
Add Ruby 3.3 to the matrix.
diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index 607a403..3bab29a 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -1,36 +1,36 @@ name: Ruby on: push: branches: [ main ] paths-ignore: - '**/*.md' pull_request: branches: [ main ] paths-ignore: - '**/*.md' workflow_dispatch: jobs: test: strategy: matrix: - ruby-version: ['2.6', '2.7', '3.0', '3.1', '3.2', 'jruby', 'truffleruby'] + ruby-version: ['2.6', '2.7', '3.0', '3.1', '3.2', '3.3', 'jruby', 'truffleruby'] platform: [ubuntu-latest, macos-latest, windows-latest] exclude: - ruby-version: truffleruby platform: windows-latest - ruby-version: jruby platform: windows-latest - ruby-version: 3.0 platform: windows-latest runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true - name: Run tests run: bundle exec rake
djberg96/sys-uptime
b3c52bc4249a1edfe86bf410cbb4cfb2030a8e3e
Very minor readme formatting update.
diff --git a/README.md b/README.md index 640ca52..d694a91 100644 --- a/README.md +++ b/README.md @@ -1,74 +1,74 @@ [![Ruby](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml/badge.svg)](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml) ## Description A Ruby interface for getting system uptime information. ## Prerequisites ffi 0.1.0 or later on Unixy platforms. ## Installation `gem install sys-uptime` ## Adding the trusted cert `gem cert --add <(curl -Ls https://raw.githubusercontent.com/djberg96/sys-uptime/main/certs/djberg96_pub.pem)` ## Synopsis ```ruby require 'sys-uptime' include Sys # Get everything p Uptime.uptime p Uptime.dhms.join(', ') # Get individual units p Uptime.days p Uptime.hours p Uptime.minutes p Uptime.seconds # Get the boot time p Uptime.boot_time ``` ## Notes On MS Windows the `Uptime.uptime` and `Uptime.boot_time` methods optionally takes a host name as a single argument. The default is localhost. The current time, users and load average are not included in this library module, even though you may be used to seeing them with the command -line version of +uptime+. +line version of `uptime`. ## Known Bugs None that I am aware of. Please log any bugs you find on the project website at https://github.com/djberg96/sys-uptime. ## Questions "Doesn't Struct::Tms do this?" - No. ## License Apache-2.0 ## Copyright Copyright 2002-2023, Daniel J. Berger All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Ruby itself. ## Warranty This library is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. ## Acknowledgements Andrea Fazzi for help with the FFI version. Mike Hall for help with the BSD side of things for the original C code. Ola Eriksson, whose source code I shamelessly plagiarized to get a better implementation for systems that have the utmpx.h header file for the original C code. ## Author Daniel J. Berger
djberg96/sys-uptime
af5a0b8bed4e1c541c88e7e1d9d729bcfa6945a6
Add trusted cert installation instructions.
diff --git a/README.md b/README.md index 34b333e..640ca52 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,74 @@ [![Ruby](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml/badge.svg)](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml) ## Description A Ruby interface for getting system uptime information. ## Prerequisites ffi 0.1.0 or later on Unixy platforms. ## Installation `gem install sys-uptime` +## Adding the trusted cert +`gem cert --add <(curl -Ls https://raw.githubusercontent.com/djberg96/sys-uptime/main/certs/djberg96_pub.pem)` + ## Synopsis ```ruby require 'sys-uptime' include Sys # Get everything p Uptime.uptime p Uptime.dhms.join(', ') # Get individual units p Uptime.days p Uptime.hours p Uptime.minutes p Uptime.seconds # Get the boot time p Uptime.boot_time ``` ## Notes On MS Windows the `Uptime.uptime` and `Uptime.boot_time` methods optionally takes a host name as a single argument. The default is localhost. The current time, users and load average are not included in this library module, even though you may be used to seeing them with the command line version of +uptime+. ## Known Bugs None that I am aware of. Please log any bugs you find on the project website at https://github.com/djberg96/sys-uptime. ## Questions "Doesn't Struct::Tms do this?" - No. ## License Apache-2.0 ## Copyright Copyright 2002-2023, Daniel J. Berger All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Ruby itself. ## Warranty This library is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. ## Acknowledgements Andrea Fazzi for help with the FFI version. Mike Hall for help with the BSD side of things for the original C code. Ola Eriksson, whose source code I shamelessly plagiarized to get a better implementation for systems that have the utmpx.h header file for the original C code. ## Author Daniel J. Berger
djberg96/sys-uptime
2b8c0153fd88fc3e584e7fb350664814b395cdac
Minor formatting update.
diff --git a/README.md b/README.md index 941392b..34b333e 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,71 @@ [![Ruby](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml/badge.svg)](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml) ## Description A Ruby interface for getting system uptime information. ## Prerequisites ffi 0.1.0 or later on Unixy platforms. ## Installation `gem install sys-uptime` ## Synopsis ```ruby require 'sys-uptime' include Sys # Get everything p Uptime.uptime p Uptime.dhms.join(', ') # Get individual units p Uptime.days p Uptime.hours p Uptime.minutes p Uptime.seconds # Get the boot time p Uptime.boot_time ``` ## Notes -On MS Windows the +Uptime.uptime+ and +Uptime.boot_time+ methods optionally +On MS Windows the `Uptime.uptime` and `Uptime.boot_time` methods optionally takes a host name as a single argument. The default is localhost. The current time, users and load average are not included in this library module, even though you may be used to seeing them with the command line version of +uptime+. ## Known Bugs None that I am aware of. Please log any bugs you find on the project website at https://github.com/djberg96/sys-uptime. ## Questions "Doesn't Struct::Tms do this?" - No. ## License Apache-2.0 ## Copyright Copyright 2002-2023, Daniel J. Berger All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Ruby itself. ## Warranty This library is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. ## Acknowledgements Andrea Fazzi for help with the FFI version. Mike Hall for help with the BSD side of things for the original C code. Ola Eriksson, whose source code I shamelessly plagiarized to get a better implementation for systems that have the utmpx.h header file for the original C code. ## Author Daniel J. Berger
djberg96/sys-uptime
4f0e817a4012e7256edff714716aeba149206911
Version bump.
diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index b1b1cf3..952fb70 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,42 +1,42 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' - spec.version = '0.7.5' + spec.version = '0.7.6' spec.author = 'Daniel J. Berger' spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'spec/sys_uptime_spec.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] if File::ALT_SEPARATOR spec.platform = Gem::Platform.new(['universal', 'mingw32']) else spec.add_dependency('ffi', '~> 1.1') end spec.add_development_dependency('rake') spec.add_development_dependency('rspec', '~> 3.9') spec.add_development_dependency('rubocop') spec.add_development_dependency('rubocop-rspec') spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/main/CHANGES.md', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'rubygems_mfa_required' => 'true', 'github_repo' => 'https://github.com/djberg96/sys-uptime' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
bebea3cdbc47c79d80d40e81974bf7e004c7f28a
Add changes for 0.7.6 and update versions, etc.
diff --git a/CHANGES.md b/CHANGES.md index 0ee5aa5..a79b3e3 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,185 +1,192 @@ +## 0.7.6 - 9-Apr-2023 +* Constructor is now officially private, as are several constants that were + never meant to be public. +* Lots of rubocop suggested updates. +* Minor refactoring for Windows. +* Minor updates, including Rakefile and gemspec metadata. + ## 0.7.5 - 29-Oct-2020 * Switched docs to markdown format. * Added a Gemfile. ## 0.7.4 - 18-Mar-2020 * Added a LICENSE file as per the requirements of the Apache-2.0 license. ## 0.7.3 - 31-Dec-2019 * Attempting to call Sys::Uptime.new will now raise an error. I thought this was already the case, but apparently one of the tests was bad. * Added explicit .rdoc extensions to various text files so that github will display them nicely. * Switched from test-unit to rspec as the testing framework of choice. * Updated the gemspec to reflect the filename updates, as well as the added development dependency. ## 0.7.2 - 4-Nov-2018 * Added metadata to the gemspec. * The VERSION constant is now frozen. * Updated cert. ## 0.7.1 - 14-May-2016 * Altered internal layout, which also fixed a require bug. Thanks go to jkburges for the spot. * Moved the VERSION constant into a single file shared by all platforms. ## 0.7.0 - 3-Oct-2015 * Changed license to Apache 2.0. * Added a cert. This gem is now signed. * Added a sys-uptime.rb file for convenience. * Gem related tasks in the Rakefile now assume Rubygems 2.x. ## 0.6.2 - 8-Nov-2014 * Minor updates to gemspec and Rakefile. ## 0.6.1 - 22-Oct-2012 * Refactored a private method in the MS Windows source. * Minor fix for one private method test. * Fixed an RbConfig vs Config warning. Thanks Pedro Carrico. ## 0.6.0 - 11-Dec-2011 * Switched Unix code to use FFI. * Removed all of the C related tasks from the Rakefile and added the gem:build and gem:install tasks. * Internal directory layout changes, with appropriate changes to the gemspec. ## 0.5.3 - 7-May-2009 * Altered the Uptime.seconds implementation on Linux so that it works with both Ruby 1.8.x and 1.9.x. Thanks go to Alexey Chebotar for the spot. ## 0.5.2 - 13-Dec-2008 * Fixed a date/time issue in the Windows version caused by Ruby itself. * Fixed the Uptime.seconds, Uptime.minutes and Uptime.hours methods on MS Windows. * Renamed the test file to 'test_sys_uptime.rb'. * Some minor updates to the Rakefile. ## 0.5.1 - 26-Jul-2007 * Fixed bug in the MS Windows version caused by incorrect parsing of an MS specific date format (caused by a bug in Ruby 1.8.6). Thanks go to Robert H. for the spot. * Inlined the Rake installation tasks, so the install.rb file has been removed. * Added an 'install_gem' Rake task, and updated the README installation instructions. ## 0.5.0 - 30-Mar-2007 * For platforms that use C code, the code now always uses the sysctl() function if supported by your system. This replaces the platform specific checks I was doing for the various BSD flavors. * Fix for OS X - the Uptime.boot_time method now works. * UptimeError is now Uptime::Error. * Improved RDoc in the uptime.c source code. * Added a Rakefile - users should now use the 'test' and 'install' rake tasks. * Updates to the MANIFEST, README and uptime.txt files. ## 0.4.5 - 19-Nov-2006 * Internal layout changes, minor doc updates and gemspec improvements. * No code changes. ## 0.4.4 - 30-Jun-2006 * Added inline rdoc documentation to the source files. * Added a gemspec. ## 0.4.3 - 18-Dec-2005 * Changed the Linux version to pure Ruby. The current method of determining uptime in unix.c does not work in Linux kernel 2.6+. So, from now on it reads out of /proc/uptime. ## 0.4.2 - 6-May-2005 * Fixed a potential boot_time bug. * Removed the version.h file. It's no longer needed since the Windows version is pure Ruby. * NetBSD 2.x and FreeBSD 5.x now supported. * Removed the INSTALL file. Installation instructions are now in the README file. * Removed the uptime.rd file. You can generate html documentation by running rdoc over the uptime.txt file. * Made most documents rdoc friendly. * Moved project to RubyForge. ## 0.4.1 - 14-Dec-2004 * Moved freebsd code into unix.c file. * Should now work past 249 days (2**31) on systems that have utmpx.h. * Fixed a bug with regards to boot_time, where it was possible that it would simply be empty. ## 0.4.0 - 8-Jul-2004 * Removed all reference to the CLK_TCK constant, as per documentation from Richard Stevens that it is deprecated and that sysconf() should be used instead (well, I knew about this, but ignored it until now). * Scrapped the C version for Windows in favor of a pure Ruby version that uses win32ole + WMI. * Added a boot_time method for Unix systems (Windows already had this). * Added an UptimeError class on Unix systems (and replaced UptimeException on Windows). * Modified an internal function to raise an UptimeError if the times() function fails. Also, it now returns an unsigned long instead of a plain long. * Replaced the two different test suites with a single, unified test suite. * Cleaned up the extconf.rb script. I now assume that TestUnit is installed. * Removed the load_avg method (which was never advertised and which I hope you weren't using). You can find a load_avg method in the sys-cpu package. * Changed uptime.rd2 to uptime.rd to be consistent with my other packages. * Removed the uptime.html file - you may generate that on your own. * Added warranty and license info. ## 0.3.2 - 30-Dec-2003 * Cleaned up some warnings that showed up with -Wall on some unix platforms (int vs long format, explicit include) * Minor test suite and extconf.rb changes ## 0.3.1 - 25-Jun-2003 * Modified test files to handle HP-UX extensions * Minor doc updates * Added the dhms() method. Actually, this was in the 0.3.0 release, I just forgot to mention it in this file :) ## 0.3.0 - 22-Jun-2003 * Added OS X support - thanks go to Mike Hall for the patch * Fixed incorrect values in FreeBSD (again Mike Hall) * Modified tc_unix.rb test suite to handle OS X, along with a bit * of minor cleanup * Removed VERSION class method. Use the constant instead * Separated FreeBSD/OS X source into its own file (freebsd.c). The #ifdefs were starting to get too ugly for me ## 0.2.1 - 13-May-2003 * Fixed bug in extconf.rb file, and made some major changes * Modified test.rb for those without TestUnit * Modified TestUnit tests - some bogus tests were removed * Added a README file with some additional info * Created a version.h file, so that I can keep the VERSION number in one place * Docs automatically included in doc directory (i.e. no more interactive document creation) ## 0.2.0 - 13-Mar-2003 * Added MS Windows support * Added a VERSION constant * Added a test suite (for those with TestUnit installed) * Internal directory layout change * uptime.c is now split into unix.c and windows.c (and linked appropriately) * Changelog and Manifest are now CHANGES and MANIFEST, respectively * Many changes to extconf.rb ## 0.1.3 - 6-Jan-2003 * Added a VERSION class method * Added a copyright notice * Fixed up the docs a bit and moved them to the doc directory * Changed the tarball name to match the RAA package name * Modified test.rb script to make it better * Changed install instructions slightly ## 0.1.2 - 25-Aug-2002 * Slight change to preprocessor commands to avoid redefining CLK_TCK on those systems that define it in time.h * Added an INSTALL file ## 0.1.1 - 21-Jun-2002 * The CLK_TCK constant wasn't necessarily being set correctly, which could lead to some odd results. This has been fixed. ## 0.1.0 - 17-Jun-2002 * Initial release diff --git a/lib/sys/uptime.rb b/lib/sys/uptime.rb index 3e1a6f1..17d542a 100644 --- a/lib/sys/uptime.rb +++ b/lib/sys/uptime.rb @@ -1,18 +1,18 @@ # frozen_string_literal: true if File::ALT_SEPARATOR require_relative 'windows/sys/uptime' else require_relative 'unix/sys/uptime' end # The Sys module serves as a namespace only. module Sys # The Uptime class serves as a base singleton class to hang uptime related methods on. class Uptime # The version of the sys-uptime library - VERSION = '0.7.5' + VERSION = '0.7.6' private_class_method :new end end diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index 8808719..d88b786 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,111 +1,111 @@ # frozen_string_literal: true ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' -describe Sys::Uptime do +RSpec.describe Sys::Uptime do let(:plausible_seconds) { ENV['CI'] ? 30 : 120 } example 'version is set to expected value' do - expect(Sys::Uptime::VERSION).to eql('0.7.5') + expect(Sys::Uptime::VERSION).to eql('0.7.6') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example 'constructor is private' do expect{ described_class.new }.to raise_error(NoMethodError) end example 'seconds method basic functionality' do expect(described_class).to respond_to(:seconds) expect{ described_class.seconds }.not_to raise_error end example 'seconds method returns a plausible value' do expect(described_class.seconds).to be_a(Integer) expect(described_class.seconds).to be > plausible_seconds end example 'minutes method basic functionality' do expect(described_class).to respond_to(:minutes) expect{ described_class.minutes }.not_to raise_error end example 'minutes method returns a plausible value', :unless => ENV.fetch('CI', nil) do expect(described_class.minutes).to be_a(Integer) expect(described_class.minutes).to be > 3 end example 'hours method basic functionality' do expect(described_class).to respond_to(:hours) expect{ described_class.hours }.not_to raise_error end example 'hours method returns a plausible value' do expect(described_class.hours).to be_a(Integer) expect(described_class.hours).to be >= 0 end example 'days method basic functionality' do expect(described_class).to respond_to(:days) expect{ described_class.days }.not_to raise_error end example 'days method returns a plausible value' do expect(described_class.days).to be_a(Integer) expect(described_class.days).to be >= 0 end example 'uptime method basic functionality' do expect(described_class).to respond_to(:uptime) expect{ described_class.uptime }.not_to raise_error end example 'uptime method returns a non-empty string' do expect(described_class.uptime).to be_a(String) expect(described_class.uptime.empty?).to be(false) end example 'uptime method does not accept any arguments', :unless => File::ALT_SEPARATOR do expect{ described_class.uptime(1) }.to raise_error(ArgumentError) end example 'uptime accepts a host name on Windows', :if => File::ALT_SEPARATOR do expect{ described_class.uptime(Socket.gethostname) }.not_to raise_error end example 'dhms method basic functionality' do expect(described_class).to respond_to(:dhms) expect{ described_class.dhms }.not_to raise_error expect(described_class.dhms).to be_a(Array) end example 'dhms method returns an array of four elements' do expect(described_class.dhms).not_to be_empty expect(described_class.dhms.length).to eq(4) end example 'boot_time method basic functionality' do expect(described_class).to respond_to(:boot_time) expect{ described_class.boot_time }.not_to raise_error end example 'boot_time method returns a Time object' do expect(described_class.boot_time).to be_a(Time) end example 'Uptime class cannot be instantiated' do expect{ described_class.new }.to raise_error(StandardError) end example 'Ensure that ffi functions are private' do methods = described_class.methods(false).map(&:to_s) expect(methods).not_to include('time', 'times') end end diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 939a9bf..b1b1cf3 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,41 +1,42 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' spec.version = '0.7.5' spec.author = 'Daniel J. Berger' spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'spec/sys_uptime_spec.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] if File::ALT_SEPARATOR spec.platform = Gem::Platform.new(['universal', 'mingw32']) else spec.add_dependency('ffi', '~> 1.1') end spec.add_development_dependency('rake') spec.add_development_dependency('rspec', '~> 3.9') spec.add_development_dependency('rubocop') spec.add_development_dependency('rubocop-rspec') spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/main/CHANGES.md', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki', - 'rubygems_mfa_required' => 'true' + 'rubygems_mfa_required' => 'true', + 'github_repo' => 'https://github.com/djberg96/sys-uptime' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
caafeafbe23e0f44684d012faaee051a32710c63
Apply some rubocop updates.
diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index 57999fe..8808719 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,111 +1,111 @@ # frozen_string_literal: true ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do let(:plausible_seconds) { ENV['CI'] ? 30 : 120 } example 'version is set to expected value' do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example 'constructor is private' do expect{ described_class.new }.to raise_error(NoMethodError) end example 'seconds method basic functionality' do expect(described_class).to respond_to(:seconds) expect{ described_class.seconds }.not_to raise_error end example 'seconds method returns a plausible value' do - expect(described_class.seconds).to be_kind_of(Integer) + expect(described_class.seconds).to be_a(Integer) expect(described_class.seconds).to be > plausible_seconds end example 'minutes method basic functionality' do expect(described_class).to respond_to(:minutes) expect{ described_class.minutes }.not_to raise_error end - example 'minutes method returns a plausible value', :unless => ENV['CI'] do - expect(described_class.minutes).to be_kind_of(Integer) + example 'minutes method returns a plausible value', :unless => ENV.fetch('CI', nil) do + expect(described_class.minutes).to be_a(Integer) expect(described_class.minutes).to be > 3 end example 'hours method basic functionality' do expect(described_class).to respond_to(:hours) expect{ described_class.hours }.not_to raise_error end example 'hours method returns a plausible value' do - expect(described_class.hours).to be_kind_of(Integer) + expect(described_class.hours).to be_a(Integer) expect(described_class.hours).to be >= 0 end example 'days method basic functionality' do expect(described_class).to respond_to(:days) expect{ described_class.days }.not_to raise_error end example 'days method returns a plausible value' do - expect(described_class.days).to be_kind_of(Integer) + expect(described_class.days).to be_a(Integer) expect(described_class.days).to be >= 0 end example 'uptime method basic functionality' do expect(described_class).to respond_to(:uptime) expect{ described_class.uptime }.not_to raise_error end example 'uptime method returns a non-empty string' do - expect(described_class.uptime).to be_kind_of(String) + expect(described_class.uptime).to be_a(String) expect(described_class.uptime.empty?).to be(false) end example 'uptime method does not accept any arguments', :unless => File::ALT_SEPARATOR do expect{ described_class.uptime(1) }.to raise_error(ArgumentError) end example 'uptime accepts a host name on Windows', :if => File::ALT_SEPARATOR do expect{ described_class.uptime(Socket.gethostname) }.not_to raise_error end example 'dhms method basic functionality' do expect(described_class).to respond_to(:dhms) expect{ described_class.dhms }.not_to raise_error - expect(described_class.dhms).to be_kind_of(Array) + expect(described_class.dhms).to be_a(Array) end example 'dhms method returns an array of four elements' do expect(described_class.dhms).not_to be_empty expect(described_class.dhms.length).to eq(4) end example 'boot_time method basic functionality' do expect(described_class).to respond_to(:boot_time) expect{ described_class.boot_time }.not_to raise_error end example 'boot_time method returns a Time object' do - expect(described_class.boot_time).to be_kind_of(Time) + expect(described_class.boot_time).to be_a(Time) end example 'Uptime class cannot be instantiated' do expect{ described_class.new }.to raise_error(StandardError) end example 'Ensure that ffi functions are private' do methods = described_class.methods(false).map(&:to_s) expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
2c921a5a32a488335ec022ffe251c6f548bb595f
Formatting, update copyright.
diff --git a/README.md b/README.md index 335d2a6..941392b 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,71 @@ [![Ruby](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml/badge.svg)](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml) ## Description A Ruby interface for getting system uptime information. ## Prerequisites ffi 0.1.0 or later on Unixy platforms. ## Installation `gem install sys-uptime` ## Synopsis -``` +```ruby require 'sys-uptime' include Sys # Get everything p Uptime.uptime p Uptime.dhms.join(', ') # Get individual units p Uptime.days p Uptime.hours p Uptime.minutes p Uptime.seconds # Get the boot time p Uptime.boot_time ``` ## Notes On MS Windows the +Uptime.uptime+ and +Uptime.boot_time+ methods optionally takes a host name as a single argument. The default is localhost. The current time, users and load average are not included in this library module, even though you may be used to seeing them with the command line version of +uptime+. ## Known Bugs None that I am aware of. Please log any bugs you find on the project website at https://github.com/djberg96/sys-uptime. ## Questions "Doesn't Struct::Tms do this?" - No. ## License Apache-2.0 ## Copyright -Copyright 2002-2019, Daniel J. Berger +Copyright 2002-2023, Daniel J. Berger All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Ruby itself. ## Warranty This library is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. ## Acknowledgements Andrea Fazzi for help with the FFI version. Mike Hall for help with the BSD side of things for the original C code. Ola Eriksson, whose source code I shamelessly plagiarized to get a better implementation for systems that have the utmpx.h header file for the original C code. ## Author Daniel J. Berger
djberg96/sys-uptime
dba57624cb7737bae035841130985f674d3ceeee
Add 3.1 and 3.2 to the matrix, update actions.
diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index c21af72..607a403 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -1,36 +1,36 @@ name: Ruby on: push: branches: [ main ] paths-ignore: - '**/*.md' pull_request: branches: [ main ] paths-ignore: - '**/*.md' workflow_dispatch: jobs: test: strategy: matrix: - ruby-version: ['2.6', '2.7', '3.0', 'jruby', 'truffleruby'] + ruby-version: ['2.6', '2.7', '3.0', '3.1', '3.2', 'jruby', 'truffleruby'] platform: [ubuntu-latest, macos-latest, windows-latest] exclude: - ruby-version: truffleruby platform: windows-latest - ruby-version: jruby platform: windows-latest - ruby-version: 3.0 platform: windows-latest runs-on: ${{ matrix.platform }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true - name: Run tests run: bundle exec rake
djberg96/sys-uptime
dfbdf84416bd272a17cf97a5205590fc22a1212f
Simplify paths-ignore, add workflow_dispatch.
diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index 3ae5519..c21af72 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -1,39 +1,36 @@ name: Ruby on: push: branches: [ main ] paths-ignore: - - '**/README.md' - - '**/CHANGES.md' - - '**/MANIFEST.md' + - '**/*.md' pull_request: branches: [ main ] paths-ignore: - - '**/README.md' - - '**/CHANGES.md' - - '**/MANIFEST.md' + - '**/*.md' + workflow_dispatch: jobs: test: strategy: matrix: ruby-version: ['2.6', '2.7', '3.0', 'jruby', 'truffleruby'] platform: [ubuntu-latest, macos-latest, windows-latest] exclude: - ruby-version: truffleruby platform: windows-latest - ruby-version: jruby platform: windows-latest - ruby-version: 3.0 platform: windows-latest runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v2 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true - name: Run tests run: bundle exec rake
djberg96/sys-uptime
4f7b2c290ec93a08d89e0907cf24709bbae92299
Add rubygems_mfa_required to metadata.
diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 2955397..939a9bf 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,40 +1,41 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' spec.version = '0.7.5' spec.author = 'Daniel J. Berger' spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'spec/sys_uptime_spec.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] if File::ALT_SEPARATOR spec.platform = Gem::Platform.new(['universal', 'mingw32']) else spec.add_dependency('ffi', '~> 1.1') end spec.add_development_dependency('rake') spec.add_development_dependency('rspec', '~> 3.9') spec.add_development_dependency('rubocop') spec.add_development_dependency('rubocop-rspec') spec.metadata = { - 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', - 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', - 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/main/CHANGES.md', - 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', - 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', - 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki' + 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', + 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', + 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/main/CHANGES.md', + 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', + 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', + 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki', + 'rubygems_mfa_required' => 'true' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
0946d2063fa346762cb14519074e1c1a86a83dbf
Create FUNDING.yml
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..23157d4 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,4 @@ +# These are supported funding model platforms + +github: djberg96 +open_collective: daniel-berger
djberg96/sys-uptime
5427eb59ff135d9842e19a5e7b5cc2c17848493f
Just skip the minutes test in CI.
diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index 0d108ca..57999fe 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,115 +1,111 @@ # frozen_string_literal: true ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do let(:plausible_seconds) { ENV['CI'] ? 30 : 120 } example 'version is set to expected value' do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example 'constructor is private' do expect{ described_class.new }.to raise_error(NoMethodError) end example 'seconds method basic functionality' do expect(described_class).to respond_to(:seconds) expect{ described_class.seconds }.not_to raise_error end example 'seconds method returns a plausible value' do expect(described_class.seconds).to be_kind_of(Integer) expect(described_class.seconds).to be > plausible_seconds end example 'minutes method basic functionality' do expect(described_class).to respond_to(:minutes) expect{ described_class.minutes }.not_to raise_error end - example 'minutes method returns a plausible value' do + example 'minutes method returns a plausible value', :unless => ENV['CI'] do expect(described_class.minutes).to be_kind_of(Integer) - if ENV['CI'] - expect(described_class.minutes).to be >= 0 - else - expect(described_class.minutes).to be > 0 - end + expect(described_class.minutes).to be > 3 end example 'hours method basic functionality' do expect(described_class).to respond_to(:hours) expect{ described_class.hours }.not_to raise_error end example 'hours method returns a plausible value' do expect(described_class.hours).to be_kind_of(Integer) expect(described_class.hours).to be >= 0 end example 'days method basic functionality' do expect(described_class).to respond_to(:days) expect{ described_class.days }.not_to raise_error end example 'days method returns a plausible value' do expect(described_class.days).to be_kind_of(Integer) expect(described_class.days).to be >= 0 end example 'uptime method basic functionality' do expect(described_class).to respond_to(:uptime) expect{ described_class.uptime }.not_to raise_error end example 'uptime method returns a non-empty string' do expect(described_class.uptime).to be_kind_of(String) expect(described_class.uptime.empty?).to be(false) end example 'uptime method does not accept any arguments', :unless => File::ALT_SEPARATOR do expect{ described_class.uptime(1) }.to raise_error(ArgumentError) end example 'uptime accepts a host name on Windows', :if => File::ALT_SEPARATOR do expect{ described_class.uptime(Socket.gethostname) }.not_to raise_error end example 'dhms method basic functionality' do expect(described_class).to respond_to(:dhms) expect{ described_class.dhms }.not_to raise_error expect(described_class.dhms).to be_kind_of(Array) end example 'dhms method returns an array of four elements' do expect(described_class.dhms).not_to be_empty expect(described_class.dhms.length).to eq(4) end example 'boot_time method basic functionality' do expect(described_class).to respond_to(:boot_time) expect{ described_class.boot_time }.not_to raise_error end example 'boot_time method returns a Time object' do expect(described_class.boot_time).to be_kind_of(Time) end example 'Uptime class cannot be instantiated' do expect{ described_class.new }.to raise_error(StandardError) end example 'Ensure that ffi functions are private' do methods = described_class.methods(false).map(&:to_s) expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
fe2e007b90e724cbe98e150d213a3f0e16c10f22
Add rubocop dev dependencies, rake task, update rubocop config.
diff --git a/.rubocop.yml b/.rubocop.yml index cca4004..340f40f 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,52 +1,57 @@ require: rubocop-rspec RSpec/MultipleExpectations: Max: 4 RSpec/ContextWording: Enabled: false RSpec/FilePath: SpecSuffixOnly: true RSpec/InstanceVariable: Enabled: false AllCops: NewCops: enable + Exclude: + - sys-uptime.gemspec + - Gemfile + - Rakefile + - examples/*.rb Lint/AssignmentInCondition: Enabled: false Style/HashSyntax: Enabled: false Style/MethodCallWithoutArgsParentheses: Enabled: false Style/NumericLiterals: Enabled: false Style/NumericPredicate: Enabled: false Style/ClassAndModuleChildren: Enabled: false Style/ConditionalAssignment: Enabled: false Style/IfUnlessModifier: Enabled: false Layout/EmptyLineAfterGuardClause: Enabled: false Layout/CaseIndentation: IndentOneStep: true Layout/SpaceBeforeBlockBraces: Enabled: false Metrics/AbcSize: Enabled: false Metrics/BlockLength: IgnoredMethods: ['describe', 'context'] Metrics/ClassLength: Enabled: false Metrics/MethodLength: Enabled: false Metrics/CyclomaticComplexity: Enabled: false Metrics/PerceivedComplexity: Enabled: false Naming/RescuedExceptionsVariableName: PreferredName: 'err' Naming/FileName: Exclude: - 'lib/sys-uptime.rb' diff --git a/Rakefile b/Rakefile index 37dc9d6..a0132b6 100644 --- a/Rakefile +++ b/Rakefile @@ -1,27 +1,30 @@ require 'rake' require 'rake/clean' require 'rake/testtask' require 'rspec/core/rake_task' +require 'rubocop/rake_task' CLEAN.include("**/*.gem", "**/*.rbx", "**/*.rbc", "**/*.lock") namespace 'gem' do desc 'Build the sys-uptime gem' task :create => [:clean] do require 'rubygems/package' spec = Gem::Specification.load('sys-uptime.gemspec') spec.signing_key = File.join(Dir.home, '.ssh', 'gem-private_key.pem') Gem::Package.build(spec) end desc 'Install the sys-uptime gem' task :install => [:create] do file = Dir["*.gem"].first sh "gem install -l #{file}" end end +RuboCop::RakeTask.new + desc "Run the test suite" RSpec::Core::RakeTask.new(:spec) task :default => :spec diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 10f1cf7..2955397 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,38 +1,40 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' spec.version = '0.7.5' spec.author = 'Daniel J. Berger' spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'spec/sys_uptime_spec.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] if File::ALT_SEPARATOR spec.platform = Gem::Platform.new(['universal', 'mingw32']) else spec.add_dependency('ffi', '~> 1.1') end spec.add_development_dependency('rake') spec.add_development_dependency('rspec', '~> 3.9') + spec.add_development_dependency('rubocop') + spec.add_development_dependency('rubocop-rspec') spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/main/CHANGES.md', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
973169beb4a67c117aaceca86b1a61c93faa2093
Disable hash syntax cop, add frozen string literal to spec.
diff --git a/.rubocop.yml b/.rubocop.yml index 1c08f9a..cca4004 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,50 +1,52 @@ require: rubocop-rspec RSpec/MultipleExpectations: Max: 4 RSpec/ContextWording: Enabled: false RSpec/FilePath: SpecSuffixOnly: true RSpec/InstanceVariable: Enabled: false AllCops: NewCops: enable Lint/AssignmentInCondition: Enabled: false +Style/HashSyntax: + Enabled: false Style/MethodCallWithoutArgsParentheses: Enabled: false Style/NumericLiterals: Enabled: false Style/NumericPredicate: Enabled: false Style/ClassAndModuleChildren: Enabled: false Style/ConditionalAssignment: Enabled: false Style/IfUnlessModifier: Enabled: false Layout/EmptyLineAfterGuardClause: Enabled: false Layout/CaseIndentation: IndentOneStep: true Layout/SpaceBeforeBlockBraces: Enabled: false Metrics/AbcSize: Enabled: false Metrics/BlockLength: IgnoredMethods: ['describe', 'context'] Metrics/ClassLength: Enabled: false Metrics/MethodLength: Enabled: false Metrics/CyclomaticComplexity: Enabled: false Metrics/PerceivedComplexity: Enabled: false Naming/RescuedExceptionsVariableName: PreferredName: 'err' Naming/FileName: Exclude: - 'lib/sys-uptime.rb' diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index 54db9f2..0d108ca 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,113 +1,115 @@ +# frozen_string_literal: true + ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do let(:plausible_seconds) { ENV['CI'] ? 30 : 120 } example 'version is set to expected value' do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example 'constructor is private' do expect{ described_class.new }.to raise_error(NoMethodError) end example 'seconds method basic functionality' do expect(described_class).to respond_to(:seconds) expect{ described_class.seconds }.not_to raise_error end example 'seconds method returns a plausible value' do expect(described_class.seconds).to be_kind_of(Integer) expect(described_class.seconds).to be > plausible_seconds end example 'minutes method basic functionality' do expect(described_class).to respond_to(:minutes) expect{ described_class.minutes }.not_to raise_error end example 'minutes method returns a plausible value' do expect(described_class.minutes).to be_kind_of(Integer) if ENV['CI'] expect(described_class.minutes).to be >= 0 else expect(described_class.minutes).to be > 0 end end example 'hours method basic functionality' do expect(described_class).to respond_to(:hours) expect{ described_class.hours }.not_to raise_error end example 'hours method returns a plausible value' do expect(described_class.hours).to be_kind_of(Integer) expect(described_class.hours).to be >= 0 end example 'days method basic functionality' do expect(described_class).to respond_to(:days) expect{ described_class.days }.not_to raise_error end example 'days method returns a plausible value' do expect(described_class.days).to be_kind_of(Integer) expect(described_class.days).to be >= 0 end example 'uptime method basic functionality' do expect(described_class).to respond_to(:uptime) expect{ described_class.uptime }.not_to raise_error end example 'uptime method returns a non-empty string' do expect(described_class.uptime).to be_kind_of(String) expect(described_class.uptime.empty?).to be(false) end example 'uptime method does not accept any arguments', :unless => File::ALT_SEPARATOR do expect{ described_class.uptime(1) }.to raise_error(ArgumentError) end example 'uptime accepts a host name on Windows', :if => File::ALT_SEPARATOR do expect{ described_class.uptime(Socket.gethostname) }.not_to raise_error end example 'dhms method basic functionality' do expect(described_class).to respond_to(:dhms) expect{ described_class.dhms }.not_to raise_error expect(described_class.dhms).to be_kind_of(Array) end example 'dhms method returns an array of four elements' do expect(described_class.dhms).not_to be_empty expect(described_class.dhms.length).to eq(4) end example 'boot_time method basic functionality' do expect(described_class).to respond_to(:boot_time) expect{ described_class.boot_time }.not_to raise_error end example 'boot_time method returns a Time object' do expect(described_class.boot_time).to be_kind_of(Time) end example 'Uptime class cannot be instantiated' do expect{ described_class.new }.to raise_error(StandardError) end example 'Ensure that ffi functions are private' do methods = described_class.methods(false).map(&:to_s) expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
8a94a98271a830489e218f9d7f494d2b03c5b590
Use nicer map call.
diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index e77a180..54db9f2 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,113 +1,113 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do let(:plausible_seconds) { ENV['CI'] ? 30 : 120 } example 'version is set to expected value' do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example 'constructor is private' do expect{ described_class.new }.to raise_error(NoMethodError) end example 'seconds method basic functionality' do expect(described_class).to respond_to(:seconds) expect{ described_class.seconds }.not_to raise_error end example 'seconds method returns a plausible value' do expect(described_class.seconds).to be_kind_of(Integer) expect(described_class.seconds).to be > plausible_seconds end example 'minutes method basic functionality' do expect(described_class).to respond_to(:minutes) expect{ described_class.minutes }.not_to raise_error end example 'minutes method returns a plausible value' do expect(described_class.minutes).to be_kind_of(Integer) if ENV['CI'] expect(described_class.minutes).to be >= 0 else expect(described_class.minutes).to be > 0 end end example 'hours method basic functionality' do expect(described_class).to respond_to(:hours) expect{ described_class.hours }.not_to raise_error end example 'hours method returns a plausible value' do expect(described_class.hours).to be_kind_of(Integer) expect(described_class.hours).to be >= 0 end example 'days method basic functionality' do expect(described_class).to respond_to(:days) expect{ described_class.days }.not_to raise_error end example 'days method returns a plausible value' do expect(described_class.days).to be_kind_of(Integer) expect(described_class.days).to be >= 0 end example 'uptime method basic functionality' do expect(described_class).to respond_to(:uptime) expect{ described_class.uptime }.not_to raise_error end example 'uptime method returns a non-empty string' do expect(described_class.uptime).to be_kind_of(String) expect(described_class.uptime.empty?).to be(false) end example 'uptime method does not accept any arguments', :unless => File::ALT_SEPARATOR do expect{ described_class.uptime(1) }.to raise_error(ArgumentError) end example 'uptime accepts a host name on Windows', :if => File::ALT_SEPARATOR do expect{ described_class.uptime(Socket.gethostname) }.not_to raise_error end example 'dhms method basic functionality' do expect(described_class).to respond_to(:dhms) expect{ described_class.dhms }.not_to raise_error expect(described_class.dhms).to be_kind_of(Array) end example 'dhms method returns an array of four elements' do expect(described_class.dhms).not_to be_empty expect(described_class.dhms.length).to eq(4) end example 'boot_time method basic functionality' do expect(described_class).to respond_to(:boot_time) expect{ described_class.boot_time }.not_to raise_error end example 'boot_time method returns a Time object' do expect(described_class.boot_time).to be_kind_of(Time) end example 'Uptime class cannot be instantiated' do expect{ described_class.new }.to raise_error(StandardError) end example 'Ensure that ffi functions are private' do - methods = described_class.methods(false).map{ |e| e.to_s } + methods = described_class.methods(false).map(&:to_s) expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
e4f7d6be3d7ff51d110c6381c83fcc2bf6490aac
Use eq instead of eql.
diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index 841a73d..e77a180 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,113 +1,113 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do let(:plausible_seconds) { ENV['CI'] ? 30 : 120 } example 'version is set to expected value' do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example 'constructor is private' do expect{ described_class.new }.to raise_error(NoMethodError) end example 'seconds method basic functionality' do expect(described_class).to respond_to(:seconds) expect{ described_class.seconds }.not_to raise_error end example 'seconds method returns a plausible value' do expect(described_class.seconds).to be_kind_of(Integer) expect(described_class.seconds).to be > plausible_seconds end example 'minutes method basic functionality' do expect(described_class).to respond_to(:minutes) expect{ described_class.minutes }.not_to raise_error end example 'minutes method returns a plausible value' do expect(described_class.minutes).to be_kind_of(Integer) if ENV['CI'] expect(described_class.minutes).to be >= 0 else expect(described_class.minutes).to be > 0 end end example 'hours method basic functionality' do expect(described_class).to respond_to(:hours) expect{ described_class.hours }.not_to raise_error end example 'hours method returns a plausible value' do expect(described_class.hours).to be_kind_of(Integer) expect(described_class.hours).to be >= 0 end example 'days method basic functionality' do expect(described_class).to respond_to(:days) expect{ described_class.days }.not_to raise_error end example 'days method returns a plausible value' do expect(described_class.days).to be_kind_of(Integer) expect(described_class.days).to be >= 0 end example 'uptime method basic functionality' do expect(described_class).to respond_to(:uptime) expect{ described_class.uptime }.not_to raise_error end example 'uptime method returns a non-empty string' do expect(described_class.uptime).to be_kind_of(String) expect(described_class.uptime.empty?).to be(false) end example 'uptime method does not accept any arguments', :unless => File::ALT_SEPARATOR do expect{ described_class.uptime(1) }.to raise_error(ArgumentError) end example 'uptime accepts a host name on Windows', :if => File::ALT_SEPARATOR do expect{ described_class.uptime(Socket.gethostname) }.not_to raise_error end example 'dhms method basic functionality' do expect(described_class).to respond_to(:dhms) expect{ described_class.dhms }.not_to raise_error expect(described_class.dhms).to be_kind_of(Array) end example 'dhms method returns an array of four elements' do expect(described_class.dhms).not_to be_empty - expect(described_class.dhms.length).to eql(4) + expect(described_class.dhms.length).to eq(4) end example 'boot_time method basic functionality' do expect(described_class).to respond_to(:boot_time) expect{ described_class.boot_time }.not_to raise_error end example 'boot_time method returns a Time object' do expect(described_class.boot_time).to be_kind_of(Time) end example 'Uptime class cannot be instantiated' do expect{ described_class.new }.to raise_error(StandardError) end example 'Ensure that ffi functions are private' do methods = described_class.methods(false).map{ |e| e.to_s } expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
d5bb1c25e4011b1e4b18b143685b61e6cb0e23a9
Add rubocop config, apply some cop suggestions.
diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..1c08f9a --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,50 @@ +require: rubocop-rspec + +RSpec/MultipleExpectations: + Max: 4 +RSpec/ContextWording: + Enabled: false +RSpec/FilePath: + SpecSuffixOnly: true +RSpec/InstanceVariable: + Enabled: false + +AllCops: + NewCops: enable +Lint/AssignmentInCondition: + Enabled: false +Style/MethodCallWithoutArgsParentheses: + Enabled: false +Style/NumericLiterals: + Enabled: false +Style/NumericPredicate: + Enabled: false +Style/ClassAndModuleChildren: + Enabled: false +Style/ConditionalAssignment: + Enabled: false +Style/IfUnlessModifier: + Enabled: false +Layout/EmptyLineAfterGuardClause: + Enabled: false +Layout/CaseIndentation: + IndentOneStep: true +Layout/SpaceBeforeBlockBraces: + Enabled: false +Metrics/AbcSize: + Enabled: false +Metrics/BlockLength: + IgnoredMethods: ['describe', 'context'] +Metrics/ClassLength: + Enabled: false +Metrics/MethodLength: + Enabled: false +Metrics/CyclomaticComplexity: + Enabled: false +Metrics/PerceivedComplexity: + Enabled: false +Naming/RescuedExceptionsVariableName: + PreferredName: 'err' +Naming/FileName: + Exclude: + - 'lib/sys-uptime.rb' diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index 4499d9c..a0b67ef 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,220 +1,222 @@ # frozen_string_literal: true require 'ffi' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t private_class_method :strerror, :sysconf, :time, :times, :new begin attach_function :sysctl, %i[pointer uint pointer pointer pointer size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time private_constant :CTL_KERN private_constant :KERN_BOOTTIME private_constant :TICKS private_constant :BOOT_TIME class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end private_constant :Tms class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end private_constant :Timeval class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end private_constant :ExitStatus class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end private_constant :Utmpx # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i Time.now - seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, "sysctl function failed: #{strerror(FFI.errno)}" end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i + # rubocop:disable Lint/RescueException begin File.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end + # rubocop:enable Lint/RescueException elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, "sysctl function failed: #{strerror(FFI.errno)}" end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 secs -= days * 86400 hours = secs / 3600 secs -= hours * 3600 mins = secs / 60 secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end diff --git a/lib/sys/uptime.rb b/lib/sys/uptime.rb index f71e1b4..3e1a6f1 100644 --- a/lib/sys/uptime.rb +++ b/lib/sys/uptime.rb @@ -1,16 +1,18 @@ # frozen_string_literal: true if File::ALT_SEPARATOR require_relative 'windows/sys/uptime' else require_relative 'unix/sys/uptime' end +# The Sys module serves as a namespace only. module Sys + # The Uptime class serves as a base singleton class to hang uptime related methods on. class Uptime # The version of the sys-uptime library VERSION = '0.7.5' private_class_method :new end end diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index 76c1c5c..841a73d 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,113 +1,113 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do let(:plausible_seconds) { ENV['CI'] ? 30 : 120 } - example "version is set to expected value" do + example 'version is set to expected value' do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end - example "constructor is private" do + example 'constructor is private' do expect{ described_class.new }.to raise_error(NoMethodError) end - example "seconds method basic functionality" do - expect(Sys::Uptime).to respond_to(:seconds) - expect{ Sys::Uptime.seconds }.not_to raise_error + example 'seconds method basic functionality' do + expect(described_class).to respond_to(:seconds) + expect{ described_class.seconds }.not_to raise_error end - example "seconds method returns a plausible value" do - expect(Sys::Uptime.seconds).to be_kind_of(Integer) - expect(Sys::Uptime.seconds).to be > plausible_seconds + example 'seconds method returns a plausible value' do + expect(described_class.seconds).to be_kind_of(Integer) + expect(described_class.seconds).to be > plausible_seconds end - example "minutes method basic functionality" do - expect(Sys::Uptime).to respond_to(:minutes) - expect{ Sys::Uptime.minutes }.not_to raise_error + example 'minutes method basic functionality' do + expect(described_class).to respond_to(:minutes) + expect{ described_class.minutes }.not_to raise_error end - example "minutes method returns a plausible value" do - expect(Sys::Uptime.minutes).to be_kind_of(Integer) + example 'minutes method returns a plausible value' do + expect(described_class.minutes).to be_kind_of(Integer) if ENV['CI'] - expect(Sys::Uptime.minutes).to be >= 0 + expect(described_class.minutes).to be >= 0 else - expect(Sys::Uptime.minutes).to be > 0 + expect(described_class.minutes).to be > 0 end end - example "hours method basic functionality" do - expect(Sys::Uptime).to respond_to(:hours) - expect{ Sys::Uptime.hours }.not_to raise_error + example 'hours method basic functionality' do + expect(described_class).to respond_to(:hours) + expect{ described_class.hours }.not_to raise_error end - example "hours method returns a plausible value" do - expect(Sys::Uptime.hours).to be_kind_of(Integer) - expect(Sys::Uptime.hours).to be >= 0 + example 'hours method returns a plausible value' do + expect(described_class.hours).to be_kind_of(Integer) + expect(described_class.hours).to be >= 0 end - example "days method basic functionality" do - expect(Sys::Uptime).to respond_to(:days) - expect{ Sys::Uptime.days }.not_to raise_error + example 'days method basic functionality' do + expect(described_class).to respond_to(:days) + expect{ described_class.days }.not_to raise_error end - example "days method returns a plausible value" do - expect(Sys::Uptime.days).to be_kind_of(Integer) - expect(Sys::Uptime.days).to be >= 0 + example 'days method returns a plausible value' do + expect(described_class.days).to be_kind_of(Integer) + expect(described_class.days).to be >= 0 end - example "uptime method basic functionality" do - expect(Sys::Uptime).to respond_to(:uptime) - expect{ Sys::Uptime.uptime }.not_to raise_error + example 'uptime method basic functionality' do + expect(described_class).to respond_to(:uptime) + expect{ described_class.uptime }.not_to raise_error end - example "uptime method returns a non-empty string" do - expect(Sys::Uptime.uptime).to be_kind_of(String) - expect(Sys::Uptime.uptime.empty?).to be(false) + example 'uptime method returns a non-empty string' do + expect(described_class.uptime).to be_kind_of(String) + expect(described_class.uptime.empty?).to be(false) end - example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do - expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) + example 'uptime method does not accept any arguments', :unless => File::ALT_SEPARATOR do + expect{ described_class.uptime(1) }.to raise_error(ArgumentError) end - example "uptime accepts a host name on Windows", :if => File::ALT_SEPARATOR do - expect{ Sys::Uptime.uptime(Socket.gethostname) }.not_to raise_error + example 'uptime accepts a host name on Windows', :if => File::ALT_SEPARATOR do + expect{ described_class.uptime(Socket.gethostname) }.not_to raise_error end - example "dhms method basic functionality" do - expect(Sys::Uptime).to respond_to(:dhms) - expect{ Sys::Uptime.dhms }.not_to raise_error - expect(Sys::Uptime.dhms).to be_kind_of(Array) + example 'dhms method basic functionality' do + expect(described_class).to respond_to(:dhms) + expect{ described_class.dhms }.not_to raise_error + expect(described_class.dhms).to be_kind_of(Array) end - example "dhms method returns an array of four elements" do - expect(Sys::Uptime.dhms).not_to be_empty - expect(Sys::Uptime.dhms.length).to eql(4) + example 'dhms method returns an array of four elements' do + expect(described_class.dhms).not_to be_empty + expect(described_class.dhms.length).to eql(4) end - example "boot_time method basic functionality" do - expect(Sys::Uptime).to respond_to(:boot_time) - expect{ Sys::Uptime.boot_time }.not_to raise_error + example 'boot_time method basic functionality' do + expect(described_class).to respond_to(:boot_time) + expect{ described_class.boot_time }.not_to raise_error end - example "boot_time method returns a Time object" do - expect(Sys::Uptime.boot_time).to be_kind_of(Time) + example 'boot_time method returns a Time object' do + expect(described_class.boot_time).to be_kind_of(Time) end - example "Uptime class cannot be instantiated" do - expect{ Sys::Uptime.new }.to raise_error(StandardError) + example 'Uptime class cannot be instantiated' do + expect{ described_class.new }.to raise_error(StandardError) end - example "Ensure that ffi functions are private" do - methods = Sys::Uptime.methods(false).map{ |e| e.to_s } + example 'Ensure that ffi functions are private' do + methods = described_class.methods(false).map{ |e| e.to_s } expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
7b3821fffaf6dcc7903a62d5335777f39752a79b
Add 3.0, JRuby and Truffleruby to the workflow matrix.
diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index 36d2076..3ae5519 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -1,32 +1,39 @@ name: Ruby on: push: branches: [ main ] paths-ignore: - '**/README.md' - '**/CHANGES.md' - '**/MANIFEST.md' pull_request: branches: [ main ] paths-ignore: - '**/README.md' - '**/CHANGES.md' - '**/MANIFEST.md' jobs: test: strategy: matrix: - ruby-version: ['2.6', '2.7'] + ruby-version: ['2.6', '2.7', '3.0', 'jruby', 'truffleruby'] platform: [ubuntu-latest, macos-latest, windows-latest] + exclude: + - ruby-version: truffleruby + platform: windows-latest + - ruby-version: jruby + platform: windows-latest + - ruby-version: 3.0 + platform: windows-latest runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v2 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true - name: Run tests run: bundle exec rake
djberg96/sys-uptime
94b4aff211cb83faae1ed3fc4e8314ce1a7553de
Use File.read instead of IO.read.
diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index 82deb57..4499d9c 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,220 +1,220 @@ # frozen_string_literal: true require 'ffi' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t private_class_method :strerror, :sysconf, :time, :times, :new begin attach_function :sysctl, %i[pointer uint pointer pointer pointer size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time private_constant :CTL_KERN private_constant :KERN_BOOTTIME private_constant :TICKS private_constant :BOOT_TIME class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end private_constant :Tms class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end private_constant :Timeval class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end private_constant :ExitStatus class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end private_constant :Utmpx # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i Time.now - seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, "sysctl function failed: #{strerror(FFI.errno)}" end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i begin - IO.read('/proc/uptime').split.first.to_i + File.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, "sysctl function failed: #{strerror(FFI.errno)}" end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 secs -= days * 86400 hours = secs / 3600 secs -= hours * 3600 mins = secs / 60 secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end
djberg96/sys-uptime
18ed1591d47f8d8e478e60f39220c57d5ac76522
Adjust minutes test for CI.
diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index aa11aac..76c1c5c 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,109 +1,113 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do let(:plausible_seconds) { ENV['CI'] ? 30 : 120 } example "version is set to expected value" do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example "constructor is private" do expect{ described_class.new }.to raise_error(NoMethodError) end example "seconds method basic functionality" do expect(Sys::Uptime).to respond_to(:seconds) expect{ Sys::Uptime.seconds }.not_to raise_error end example "seconds method returns a plausible value" do expect(Sys::Uptime.seconds).to be_kind_of(Integer) expect(Sys::Uptime.seconds).to be > plausible_seconds end example "minutes method basic functionality" do expect(Sys::Uptime).to respond_to(:minutes) expect{ Sys::Uptime.minutes }.not_to raise_error end example "minutes method returns a plausible value" do expect(Sys::Uptime.minutes).to be_kind_of(Integer) - expect(Sys::Uptime.minutes).to be > 0 + if ENV['CI'] + expect(Sys::Uptime.minutes).to be >= 0 + else + expect(Sys::Uptime.minutes).to be > 0 + end end example "hours method basic functionality" do expect(Sys::Uptime).to respond_to(:hours) expect{ Sys::Uptime.hours }.not_to raise_error end example "hours method returns a plausible value" do expect(Sys::Uptime.hours).to be_kind_of(Integer) expect(Sys::Uptime.hours).to be >= 0 end example "days method basic functionality" do expect(Sys::Uptime).to respond_to(:days) expect{ Sys::Uptime.days }.not_to raise_error end example "days method returns a plausible value" do expect(Sys::Uptime.days).to be_kind_of(Integer) expect(Sys::Uptime.days).to be >= 0 end example "uptime method basic functionality" do expect(Sys::Uptime).to respond_to(:uptime) expect{ Sys::Uptime.uptime }.not_to raise_error end example "uptime method returns a non-empty string" do expect(Sys::Uptime.uptime).to be_kind_of(String) expect(Sys::Uptime.uptime.empty?).to be(false) end example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) end example "uptime accepts a host name on Windows", :if => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(Socket.gethostname) }.not_to raise_error end example "dhms method basic functionality" do expect(Sys::Uptime).to respond_to(:dhms) expect{ Sys::Uptime.dhms }.not_to raise_error expect(Sys::Uptime.dhms).to be_kind_of(Array) end example "dhms method returns an array of four elements" do expect(Sys::Uptime.dhms).not_to be_empty expect(Sys::Uptime.dhms.length).to eql(4) end example "boot_time method basic functionality" do expect(Sys::Uptime).to respond_to(:boot_time) expect{ Sys::Uptime.boot_time }.not_to raise_error end example "boot_time method returns a Time object" do expect(Sys::Uptime.boot_time).to be_kind_of(Time) end example "Uptime class cannot be instantiated" do expect{ Sys::Uptime.new }.to raise_error(StandardError) end example "Ensure that ffi functions are private" do methods = Sys::Uptime.methods(false).map{ |e| e.to_s } expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
c9c7f362e11e18155de85ee1a2c92f3a6066def8
Adjust the plausible seconds depending on the CI environment.
diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index a791ba5..aa11aac 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,107 +1,109 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do + let(:plausible_seconds) { ENV['CI'] ? 30 : 120 } + example "version is set to expected value" do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example "constructor is private" do expect{ described_class.new }.to raise_error(NoMethodError) end example "seconds method basic functionality" do expect(Sys::Uptime).to respond_to(:seconds) expect{ Sys::Uptime.seconds }.not_to raise_error end example "seconds method returns a plausible value" do expect(Sys::Uptime.seconds).to be_kind_of(Integer) - expect(Sys::Uptime.seconds).to be > 60 + expect(Sys::Uptime.seconds).to be > plausible_seconds end example "minutes method basic functionality" do expect(Sys::Uptime).to respond_to(:minutes) expect{ Sys::Uptime.minutes }.not_to raise_error end example "minutes method returns a plausible value" do expect(Sys::Uptime.minutes).to be_kind_of(Integer) expect(Sys::Uptime.minutes).to be > 0 end example "hours method basic functionality" do expect(Sys::Uptime).to respond_to(:hours) expect{ Sys::Uptime.hours }.not_to raise_error end example "hours method returns a plausible value" do expect(Sys::Uptime.hours).to be_kind_of(Integer) expect(Sys::Uptime.hours).to be >= 0 end example "days method basic functionality" do expect(Sys::Uptime).to respond_to(:days) expect{ Sys::Uptime.days }.not_to raise_error end example "days method returns a plausible value" do expect(Sys::Uptime.days).to be_kind_of(Integer) expect(Sys::Uptime.days).to be >= 0 end example "uptime method basic functionality" do expect(Sys::Uptime).to respond_to(:uptime) expect{ Sys::Uptime.uptime }.not_to raise_error end example "uptime method returns a non-empty string" do expect(Sys::Uptime.uptime).to be_kind_of(String) expect(Sys::Uptime.uptime.empty?).to be(false) end example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) end example "uptime accepts a host name on Windows", :if => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(Socket.gethostname) }.not_to raise_error end example "dhms method basic functionality" do expect(Sys::Uptime).to respond_to(:dhms) expect{ Sys::Uptime.dhms }.not_to raise_error expect(Sys::Uptime.dhms).to be_kind_of(Array) end example "dhms method returns an array of four elements" do expect(Sys::Uptime.dhms).not_to be_empty expect(Sys::Uptime.dhms.length).to eql(4) end example "boot_time method basic functionality" do expect(Sys::Uptime).to respond_to(:boot_time) expect{ Sys::Uptime.boot_time }.not_to raise_error end example "boot_time method returns a Time object" do expect(Sys::Uptime.boot_time).to be_kind_of(Time) end example "Uptime class cannot be instantiated" do expect{ Sys::Uptime.new }.to raise_error(StandardError) end example "Ensure that ffi functions are private" do methods = Sys::Uptime.methods(false).map{ |e| e.to_s } expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
db5ea6d7003918252b3624684c4284c4b622b5c4
Make constructor private and add a spec for that.
diff --git a/lib/sys/uptime.rb b/lib/sys/uptime.rb index 43ca2a7..f71e1b4 100644 --- a/lib/sys/uptime.rb +++ b/lib/sys/uptime.rb @@ -1,14 +1,16 @@ # frozen_string_literal: true if File::ALT_SEPARATOR require_relative 'windows/sys/uptime' else require_relative 'unix/sys/uptime' end module Sys class Uptime # The version of the sys-uptime library VERSION = '0.7.5' + + private_class_method :new end end diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index ef8be93..a791ba5 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,103 +1,107 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do example "version is set to expected value" do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end + example "constructor is private" do + expect{ described_class.new }.to raise_error(NoMethodError) + end + example "seconds method basic functionality" do expect(Sys::Uptime).to respond_to(:seconds) expect{ Sys::Uptime.seconds }.not_to raise_error end example "seconds method returns a plausible value" do expect(Sys::Uptime.seconds).to be_kind_of(Integer) expect(Sys::Uptime.seconds).to be > 60 end example "minutes method basic functionality" do expect(Sys::Uptime).to respond_to(:minutes) expect{ Sys::Uptime.minutes }.not_to raise_error end example "minutes method returns a plausible value" do expect(Sys::Uptime.minutes).to be_kind_of(Integer) expect(Sys::Uptime.minutes).to be > 0 end example "hours method basic functionality" do expect(Sys::Uptime).to respond_to(:hours) expect{ Sys::Uptime.hours }.not_to raise_error end example "hours method returns a plausible value" do expect(Sys::Uptime.hours).to be_kind_of(Integer) expect(Sys::Uptime.hours).to be >= 0 end example "days method basic functionality" do expect(Sys::Uptime).to respond_to(:days) expect{ Sys::Uptime.days }.not_to raise_error end example "days method returns a plausible value" do expect(Sys::Uptime.days).to be_kind_of(Integer) expect(Sys::Uptime.days).to be >= 0 end example "uptime method basic functionality" do expect(Sys::Uptime).to respond_to(:uptime) expect{ Sys::Uptime.uptime }.not_to raise_error end example "uptime method returns a non-empty string" do expect(Sys::Uptime.uptime).to be_kind_of(String) expect(Sys::Uptime.uptime.empty?).to be(false) end example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) end example "uptime accepts a host name on Windows", :if => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(Socket.gethostname) }.not_to raise_error end example "dhms method basic functionality" do expect(Sys::Uptime).to respond_to(:dhms) expect{ Sys::Uptime.dhms }.not_to raise_error expect(Sys::Uptime.dhms).to be_kind_of(Array) end example "dhms method returns an array of four elements" do expect(Sys::Uptime.dhms).not_to be_empty expect(Sys::Uptime.dhms.length).to eql(4) end example "boot_time method basic functionality" do expect(Sys::Uptime).to respond_to(:boot_time) expect{ Sys::Uptime.boot_time }.not_to raise_error end example "boot_time method returns a Time object" do expect(Sys::Uptime.boot_time).to be_kind_of(Time) end example "Uptime class cannot be instantiated" do expect{ Sys::Uptime.new }.to raise_error(StandardError) end example "Ensure that ffi functions are private" do methods = Sys::Uptime.methods(false).map{ |e| e.to_s } expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
506bd47db49b9fc46d50bd1a371f541defda7595
Use global gem source in Gemfile.
diff --git a/Gemfile b/Gemfile index 2db4201..851fabc 100644 --- a/Gemfile +++ b/Gemfile @@ -1,3 +1,2 @@ -source 'https://rubygems.org' do - gemspec -end +source 'https://rubygems.org' +gemspec
djberg96/sys-uptime
313daeaaf54b9b0f78c4e5da9fa242ee60128507
Add .gitignore file.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..63f1fef --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.lock
djberg96/sys-uptime
2ecd6fcb571b939e4a70ab928c24fb68057ef35b
Use Gem::Specification.load instead of manual eval in rake gem:create task.
diff --git a/Rakefile b/Rakefile index 29456c9..37dc9d6 100644 --- a/Rakefile +++ b/Rakefile @@ -1,27 +1,27 @@ require 'rake' require 'rake/clean' require 'rake/testtask' require 'rspec/core/rake_task' CLEAN.include("**/*.gem", "**/*.rbx", "**/*.rbc", "**/*.lock") namespace 'gem' do desc 'Build the sys-uptime gem' task :create => [:clean] do require 'rubygems/package' - spec = eval(IO.read('sys-uptime.gemspec')) + spec = Gem::Specification.load('sys-uptime.gemspec') spec.signing_key = File.join(Dir.home, '.ssh', 'gem-private_key.pem') Gem::Package.build(spec) end desc 'Install the sys-uptime gem' task :install => [:create] do file = Dir["*.gem"].first sh "gem install -l #{file}" end end desc "Run the test suite" RSpec::Core::RakeTask.new(:spec) task :default => :spec
djberg96/sys-uptime
9c2494f467e0584a886ebd08558d4a7453f0d763
Use itemIndex instead of one-iteration loop in boot_time on Windows.
diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index cc1471c..6b769d8 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,147 +1,144 @@ # frozen_string_literal: true require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # You cannot instantiate an instance of Sys::Uptime. private_class_method :new # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => err raise Error, err else query = 'select LastBootupTime from Win32_OperatingSystem' - results = wmi.ExecQuery(query) - results.each do |ole| - time_array = parse_ms_date(ole.LastBootupTime) - return Time.mktime(*time_array) - end + result = wmi.ExecQuery(query).itemIndex(0).LastBootupTime + Time.parse(result.split('.').first) end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # def self.hours(host = Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # def self.minutes(host = Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # def self.seconds(host = Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) (Time.now - boot_time(host)).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
62e6c22d0b7f5f75b0306cd83fb1be515dc99da7
Remove redundant freeze.
diff --git a/lib/sys/uptime.rb b/lib/sys/uptime.rb index 09f2501..43ca2a7 100644 --- a/lib/sys/uptime.rb +++ b/lib/sys/uptime.rb @@ -1,14 +1,14 @@ # frozen_string_literal: true if File::ALT_SEPARATOR require_relative 'windows/sys/uptime' else require_relative 'unix/sys/uptime' end module Sys class Uptime # The version of the sys-uptime library - VERSION = '0.7.5'.freeze + VERSION = '0.7.5' end end
djberg96/sys-uptime
71d9cc7cef76155637ac6631d51e2464c4eff52e
Remove useless private access modifier, make constants properly private.
diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index 0db48de..82deb57 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,211 +1,220 @@ # frozen_string_literal: true require 'ffi' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end - private - # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t private_class_method :strerror, :sysconf, :time, :times, :new begin attach_function :sysctl, %i[pointer uint pointer pointer pointer size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time + private_constant :CTL_KERN + private_constant :KERN_BOOTTIME + private_constant :TICKS + private_constant :BOOT_TIME + class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end + private_constant :Tms + class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end + private_constant :Timeval + class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end + private_constant :ExitStatus + class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end - public + private_constant :Utmpx # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i Time.now - seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, "sysctl function failed: #{strerror(FFI.errno)}" end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i begin IO.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, "sysctl function failed: #{strerror(FFI.errno)}" end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 secs -= days * 86400 hours = secs / 3600 secs -= hours * 3600 mins = secs / 60 secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end
djberg96/sys-uptime
4f45ccd1188d36d2019ac09b8444c6480377ef18
Remove redundant self.
diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index 6460fa7..4f0b807 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,211 +1,211 @@ # frozen_string_literal: true require 'ffi' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end private # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t private_class_method :strerror, :sysconf, :time, :times, :new begin attach_function :sysctl, %i[pointer uint pointer pointer pointer size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end public # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i - Time.now - self.seconds + Time.now - seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i begin IO.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 secs -= days * 86400 hours = secs / 3600 secs -= hours * 3600 mins = secs / 60 secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end
djberg96/sys-uptime
21a733a8710c4ddabff298497254ba082a596711
Remove spaces around operators.
diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index aeb7262..6460fa7 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,211 +1,211 @@ # frozen_string_literal: true require 'ffi' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end private # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t private_class_method :strerror, :sysconf, :time, :times, :new begin attach_function :sysctl, %i[pointer uint pointer pointer pointer size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end public # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i Time.now - self.seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i begin IO.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 - secs -= days * 86400 + secs -= days * 86400 hours = secs / 3600 - secs -= hours * 3600 - mins = secs / 60 - secs -= mins * 60 + secs -= hours * 3600 + mins = secs / 60 + secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end
djberg96/sys-uptime
c219d323bebf0b001f24b63015cb0b4077e06652
Remove blank line.
diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index 1a524e6..cc1471c 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,148 +1,147 @@ # frozen_string_literal: true require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime - # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # You cannot instantiate an instance of Sys::Uptime. private_class_method :new # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => err raise Error, err else query = 'select LastBootupTime from Win32_OperatingSystem' results = wmi.ExecQuery(query) results.each do |ole| time_array = parse_ms_date(ole.LastBootupTime) return Time.mktime(*time_array) end end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # def self.hours(host = Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # def self.minutes(host = Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # def self.seconds(host = Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) (Time.now - boot_time(host)).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
6702109b81deb666f58853b9a4feba860ddb9288
Add frozen string literal pragma.
diff --git a/lib/sys-uptime.rb b/lib/sys-uptime.rb index 671bbba..925245e 100644 --- a/lib/sys-uptime.rb +++ b/lib/sys-uptime.rb @@ -1 +1,3 @@ +# frozen_string_literal: true + require_relative 'sys/uptime' diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index 076730c..aeb7262 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,209 +1,211 @@ +# frozen_string_literal: true + require 'ffi' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end private # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t private_class_method :strerror, :sysconf, :time, :times, :new begin attach_function :sysctl, %i[pointer uint pointer pointer pointer size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end public # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i Time.now - self.seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i begin IO.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 secs -= days * 86400 hours = secs / 3600 secs -= hours * 3600 mins = secs / 60 secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end diff --git a/lib/sys/uptime.rb b/lib/sys/uptime.rb index 3e9ff03..09f2501 100644 --- a/lib/sys/uptime.rb +++ b/lib/sys/uptime.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + if File::ALT_SEPARATOR require_relative 'windows/sys/uptime' else require_relative 'unix/sys/uptime' end module Sys class Uptime # The version of the sys-uptime library VERSION = '0.7.5'.freeze end end diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index cae8404..1a524e6 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,146 +1,148 @@ +# frozen_string_literal: true + require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # You cannot instantiate an instance of Sys::Uptime. private_class_method :new # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => err raise Error, err else query = 'select LastBootupTime from Win32_OperatingSystem' results = wmi.ExecQuery(query) results.each do |ole| time_array = parse_ms_date(ole.LastBootupTime) return Time.mktime(*time_array) end end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # def self.hours(host = Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # def self.minutes(host = Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # def self.seconds(host = Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) (Time.now - boot_time(host)).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
caab5ae398f051cd1237497a07089abf918342e4
Remove blank lines around module body.
diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index 9761a04..076730c 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,210 +1,209 @@ require 'ffi' # The Sys module serves as a namespace only. module Sys - # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end private # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t private_class_method :strerror, :sysconf, :time, :times, :new begin attach_function :sysctl, %i[pointer uint pointer pointer pointer size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end public # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i Time.now - self.seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i begin IO.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 secs -= days * 86400 hours = secs / 3600 secs -= hours * 3600 mins = secs / 60 secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index b192db5..cae8404 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,147 +1,146 @@ require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys - # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # You cannot instantiate an instance of Sys::Uptime. private_class_method :new # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => err raise Error, err else query = 'select LastBootupTime from Win32_OperatingSystem' results = wmi.ExecQuery(query) results.each do |ole| time_array = parse_ms_date(ole.LastBootupTime) return Time.mktime(*time_array) end end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # def self.hours(host = Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # def self.minutes(host = Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # def self.seconds(host = Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) (Time.now - boot_time(host)).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
13220a2b0accdf292527a4e38309d103859752a5
Use single quotes for string literals.
diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index 078092b..b192db5 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,147 +1,147 @@ require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # You cannot instantiate an instance of Sys::Uptime. private_class_method :new # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => err raise Error, err else - query = "select LastBootupTime from Win32_OperatingSystem" + query = 'select LastBootupTime from Win32_OperatingSystem' results = wmi.ExecQuery(query) results.each do |ole| time_array = parse_ms_date(ole.LastBootupTime) return Time.mktime(*time_array) end end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # def self.hours(host = Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # def self.minutes(host = Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # def self.seconds(host = Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) (Time.now - boot_time(host)).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
478e5ceebfecf206dbf2b9d4ce3af3ff79b7fd11
Remove redundant return, pass host in get_seconds method.
diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index 327ccef..078092b 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,147 +1,147 @@ require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # You cannot instantiate an instance of Sys::Uptime. private_class_method :new # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => err raise Error, err else query = "select LastBootupTime from Win32_OperatingSystem" results = wmi.ExecQuery(query) results.each do |ole| time_array = parse_ms_date(ole.LastBootupTime) return Time.mktime(*time_array) end end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # def self.hours(host = Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # def self.minutes(host = Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # def self.seconds(host = Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? - return Time.parse(str.split('.').first) + Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) - (Time.now - boot_time).to_i + (Time.now - boot_time(host)).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
3b040217751ec27d7a8762234137980e5a1a65b8
Use symbol array.
diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index 87051b9..9761a04 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,210 +1,210 @@ require 'ffi' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end private # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t private_class_method :strerror, :sysconf, :time, :times, :new begin - attach_function :sysctl, [:pointer, :uint, :pointer, :pointer, :pointer, :size_t], :int + attach_function :sysctl, %i[pointer uint pointer pointer pointer size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end public # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i Time.now - self.seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i begin IO.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 secs -= days * 86400 hours = secs / 3600 secs -= hours * 3600 mins = secs / 60 secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end
djberg96/sys-uptime
f2f89b954b1fa9fde5c054416c3b009ce5fc0ca8
Use do/end for multiline blocks.
diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index 08de636..988c99e 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,147 +1,147 @@ require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # You cannot instantiate an instance of Sys::Uptime. private_class_method :new # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => e raise Error, e else query = "select LastBootupTime from Win32_OperatingSystem" results = wmi.ExecQuery(query) - results.each{ |ole| + results.each do |ole| time_array = parse_ms_date(ole.LastBootupTime) return Time.mktime(*time_array) - } + end end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # def self.hours(host = Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # def self.minutes(host = Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # def self.seconds(host = Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? return Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) (Time.now - boot_time).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
af29a12655f1f7a023b1a726c9a5c42b85927270
Add spaces to default arguments.
diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index 501876b..08de636 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,147 +1,147 @@ require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end # You cannot instantiate an instance of Sys::Uptime. private_class_method :new # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => e raise Error, e else query = "select LastBootupTime from Win32_OperatingSystem" results = wmi.ExecQuery(query) results.each{ |ole| time_array = parse_ms_date(ole.LastBootupTime) return Time.mktime(*time_array) } end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # - def self.hours(host=Socket.gethostname) + def self.hours(host = Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # - def self.minutes(host=Socket.gethostname) + def self.minutes(host = Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # - def self.seconds(host=Socket.gethostname) + def self.seconds(host = Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? return Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) (Time.now - boot_time).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
86c8339d42b40fee7ec18112f1bc8705fd2720a0
Add status badge.
diff --git a/README.md b/README.md index 5e4368e..335d2a6 100644 --- a/README.md +++ b/README.md @@ -1,69 +1,71 @@ +[![Ruby](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml/badge.svg)](https://github.com/djberg96/sys-uptime/actions/workflows/ruby.yml) + ## Description A Ruby interface for getting system uptime information. ## Prerequisites ffi 0.1.0 or later on Unixy platforms. ## Installation `gem install sys-uptime` ## Synopsis ``` require 'sys-uptime' include Sys # Get everything p Uptime.uptime p Uptime.dhms.join(', ') # Get individual units p Uptime.days p Uptime.hours p Uptime.minutes p Uptime.seconds # Get the boot time p Uptime.boot_time ``` ## Notes On MS Windows the +Uptime.uptime+ and +Uptime.boot_time+ methods optionally takes a host name as a single argument. The default is localhost. The current time, users and load average are not included in this library module, even though you may be used to seeing them with the command line version of +uptime+. ## Known Bugs None that I am aware of. Please log any bugs you find on the project website at https://github.com/djberg96/sys-uptime. ## Questions "Doesn't Struct::Tms do this?" - No. ## License Apache-2.0 ## Copyright Copyright 2002-2019, Daniel J. Berger All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Ruby itself. ## Warranty This library is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. ## Acknowledgements Andrea Fazzi for help with the FFI version. Mike Hall for help with the BSD side of things for the original C code. Ola Eriksson, whose source code I shamelessly plagiarized to get a better implementation for systems that have the utmpx.h header file for the original C code. ## Author Daniel J. Berger
djberg96/sys-uptime
03df502740343a5ac6f936184bffdd6fddde78de
Create ruby.yml
diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml new file mode 100644 index 0000000..1c7dabe --- /dev/null +++ b/.github/workflows/ruby.yml @@ -0,0 +1,42 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake +# For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby + +name: Ruby + +on: + push: + branches: [ ffi ] + paths-ignore: + - '**/README.md' + - '**/CHANGES.md' + - '**/MANIFEST.md' + pull_request: + branches: [ ffi ] + paths-ignore: + - '**/README.md' + - '**/CHANGES.md' + - '**/MANIFEST.md' + +jobs: + test: + strategy: + matrix: + ruby-version: ['2.6', '2.7'] + platform: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v2 + - name: Set up Ruby + # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, + # change this to (see https://github.com/ruby/setup-ruby#versioning): + # uses: ruby/setup-ruby@v1 + uses: ruby/setup-ruby@473e4d8fe5dd94ee328fdfca9f8c9c7afc9dae5e + with: + ruby-version: ${{ matrix.ruby-version }} + bundler-cache: true # runs 'bundle install' and caches installed gems automatically + - name: Run tests + run: bundle exec rake
djberg96/sys-uptime
37aece569a6faf6c3215081654dc02727dc6819f
Reduce plausible values in specs to account for CI envs.
diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index c59af4f..ef8be93 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,103 +1,103 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do example "version is set to expected value" do expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example "seconds method basic functionality" do expect(Sys::Uptime).to respond_to(:seconds) expect{ Sys::Uptime.seconds }.not_to raise_error end example "seconds method returns a plausible value" do expect(Sys::Uptime.seconds).to be_kind_of(Integer) - expect(Sys::Uptime.seconds).to be > 300 + expect(Sys::Uptime.seconds).to be > 60 end example "minutes method basic functionality" do expect(Sys::Uptime).to respond_to(:minutes) expect{ Sys::Uptime.minutes }.not_to raise_error end example "minutes method returns a plausible value" do expect(Sys::Uptime.minutes).to be_kind_of(Integer) - expect(Sys::Uptime.minutes).to be > 5 + expect(Sys::Uptime.minutes).to be > 0 end example "hours method basic functionality" do expect(Sys::Uptime).to respond_to(:hours) expect{ Sys::Uptime.hours }.not_to raise_error end example "hours method returns a plausible value" do expect(Sys::Uptime.hours).to be_kind_of(Integer) expect(Sys::Uptime.hours).to be >= 0 end example "days method basic functionality" do expect(Sys::Uptime).to respond_to(:days) expect{ Sys::Uptime.days }.not_to raise_error end example "days method returns a plausible value" do expect(Sys::Uptime.days).to be_kind_of(Integer) expect(Sys::Uptime.days).to be >= 0 end example "uptime method basic functionality" do expect(Sys::Uptime).to respond_to(:uptime) expect{ Sys::Uptime.uptime }.not_to raise_error end example "uptime method returns a non-empty string" do expect(Sys::Uptime.uptime).to be_kind_of(String) expect(Sys::Uptime.uptime.empty?).to be(false) end example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) end example "uptime accepts a host name on Windows", :if => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(Socket.gethostname) }.not_to raise_error end example "dhms method basic functionality" do expect(Sys::Uptime).to respond_to(:dhms) expect{ Sys::Uptime.dhms }.not_to raise_error expect(Sys::Uptime.dhms).to be_kind_of(Array) end example "dhms method returns an array of four elements" do expect(Sys::Uptime.dhms).not_to be_empty expect(Sys::Uptime.dhms.length).to eql(4) end example "boot_time method basic functionality" do expect(Sys::Uptime).to respond_to(:boot_time) expect{ Sys::Uptime.boot_time }.not_to raise_error end example "boot_time method returns a Time object" do expect(Sys::Uptime.boot_time).to be_kind_of(Time) end example "Uptime class cannot be instantiated" do expect{ Sys::Uptime.new }.to raise_error(StandardError) end example "Ensure that ffi functions are private" do methods = Sys::Uptime.methods(false).map{ |e| e.to_s } expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
f68c0fd21ca38847a0d56ae65ece591ccc0c733f
Add changes for 0.7.5, update changelog_uri.
diff --git a/CHANGES.md b/CHANGES.md index 0cbdc4b..0ee5aa5 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,181 +1,185 @@ +## 0.7.5 - 29-Oct-2020 +* Switched docs to markdown format. +* Added a Gemfile. + ## 0.7.4 - 18-Mar-2020 * Added a LICENSE file as per the requirements of the Apache-2.0 license. ## 0.7.3 - 31-Dec-2019 * Attempting to call Sys::Uptime.new will now raise an error. I thought this was already the case, but apparently one of the tests was bad. * Added explicit .rdoc extensions to various text files so that github will display them nicely. * Switched from test-unit to rspec as the testing framework of choice. * Updated the gemspec to reflect the filename updates, as well as the added development dependency. ## 0.7.2 - 4-Nov-2018 * Added metadata to the gemspec. * The VERSION constant is now frozen. * Updated cert. ## 0.7.1 - 14-May-2016 * Altered internal layout, which also fixed a require bug. Thanks go to jkburges for the spot. * Moved the VERSION constant into a single file shared by all platforms. ## 0.7.0 - 3-Oct-2015 * Changed license to Apache 2.0. * Added a cert. This gem is now signed. * Added a sys-uptime.rb file for convenience. * Gem related tasks in the Rakefile now assume Rubygems 2.x. ## 0.6.2 - 8-Nov-2014 * Minor updates to gemspec and Rakefile. ## 0.6.1 - 22-Oct-2012 * Refactored a private method in the MS Windows source. * Minor fix for one private method test. * Fixed an RbConfig vs Config warning. Thanks Pedro Carrico. ## 0.6.0 - 11-Dec-2011 * Switched Unix code to use FFI. * Removed all of the C related tasks from the Rakefile and added the gem:build and gem:install tasks. * Internal directory layout changes, with appropriate changes to the gemspec. ## 0.5.3 - 7-May-2009 * Altered the Uptime.seconds implementation on Linux so that it works with both Ruby 1.8.x and 1.9.x. Thanks go to Alexey Chebotar for the spot. ## 0.5.2 - 13-Dec-2008 * Fixed a date/time issue in the Windows version caused by Ruby itself. * Fixed the Uptime.seconds, Uptime.minutes and Uptime.hours methods on MS Windows. * Renamed the test file to 'test_sys_uptime.rb'. * Some minor updates to the Rakefile. ## 0.5.1 - 26-Jul-2007 * Fixed bug in the MS Windows version caused by incorrect parsing of an MS specific date format (caused by a bug in Ruby 1.8.6). Thanks go to Robert H. for the spot. * Inlined the Rake installation tasks, so the install.rb file has been removed. * Added an 'install_gem' Rake task, and updated the README installation instructions. ## 0.5.0 - 30-Mar-2007 * For platforms that use C code, the code now always uses the sysctl() function if supported by your system. This replaces the platform specific checks I was doing for the various BSD flavors. * Fix for OS X - the Uptime.boot_time method now works. * UptimeError is now Uptime::Error. * Improved RDoc in the uptime.c source code. * Added a Rakefile - users should now use the 'test' and 'install' rake tasks. * Updates to the MANIFEST, README and uptime.txt files. ## 0.4.5 - 19-Nov-2006 * Internal layout changes, minor doc updates and gemspec improvements. * No code changes. ## 0.4.4 - 30-Jun-2006 * Added inline rdoc documentation to the source files. * Added a gemspec. ## 0.4.3 - 18-Dec-2005 * Changed the Linux version to pure Ruby. The current method of determining uptime in unix.c does not work in Linux kernel 2.6+. So, from now on it reads out of /proc/uptime. ## 0.4.2 - 6-May-2005 * Fixed a potential boot_time bug. * Removed the version.h file. It's no longer needed since the Windows version is pure Ruby. * NetBSD 2.x and FreeBSD 5.x now supported. * Removed the INSTALL file. Installation instructions are now in the README file. * Removed the uptime.rd file. You can generate html documentation by running rdoc over the uptime.txt file. * Made most documents rdoc friendly. * Moved project to RubyForge. ## 0.4.1 - 14-Dec-2004 * Moved freebsd code into unix.c file. * Should now work past 249 days (2**31) on systems that have utmpx.h. * Fixed a bug with regards to boot_time, where it was possible that it would simply be empty. ## 0.4.0 - 8-Jul-2004 * Removed all reference to the CLK_TCK constant, as per documentation from Richard Stevens that it is deprecated and that sysconf() should be used instead (well, I knew about this, but ignored it until now). * Scrapped the C version for Windows in favor of a pure Ruby version that uses win32ole + WMI. * Added a boot_time method for Unix systems (Windows already had this). * Added an UptimeError class on Unix systems (and replaced UptimeException on Windows). * Modified an internal function to raise an UptimeError if the times() function fails. Also, it now returns an unsigned long instead of a plain long. * Replaced the two different test suites with a single, unified test suite. * Cleaned up the extconf.rb script. I now assume that TestUnit is installed. * Removed the load_avg method (which was never advertised and which I hope you weren't using). You can find a load_avg method in the sys-cpu package. * Changed uptime.rd2 to uptime.rd to be consistent with my other packages. * Removed the uptime.html file - you may generate that on your own. * Added warranty and license info. ## 0.3.2 - 30-Dec-2003 * Cleaned up some warnings that showed up with -Wall on some unix platforms (int vs long format, explicit include) * Minor test suite and extconf.rb changes ## 0.3.1 - 25-Jun-2003 * Modified test files to handle HP-UX extensions * Minor doc updates * Added the dhms() method. Actually, this was in the 0.3.0 release, I just forgot to mention it in this file :) ## 0.3.0 - 22-Jun-2003 * Added OS X support - thanks go to Mike Hall for the patch * Fixed incorrect values in FreeBSD (again Mike Hall) * Modified tc_unix.rb test suite to handle OS X, along with a bit * of minor cleanup * Removed VERSION class method. Use the constant instead * Separated FreeBSD/OS X source into its own file (freebsd.c). The #ifdefs were starting to get too ugly for me ## 0.2.1 - 13-May-2003 * Fixed bug in extconf.rb file, and made some major changes * Modified test.rb for those without TestUnit * Modified TestUnit tests - some bogus tests were removed * Added a README file with some additional info * Created a version.h file, so that I can keep the VERSION number in one place * Docs automatically included in doc directory (i.e. no more interactive document creation) ## 0.2.0 - 13-Mar-2003 * Added MS Windows support * Added a VERSION constant * Added a test suite (for those with TestUnit installed) * Internal directory layout change * uptime.c is now split into unix.c and windows.c (and linked appropriately) * Changelog and Manifest are now CHANGES and MANIFEST, respectively * Many changes to extconf.rb ## 0.1.3 - 6-Jan-2003 * Added a VERSION class method * Added a copyright notice * Fixed up the docs a bit and moved them to the doc directory * Changed the tarball name to match the RAA package name * Modified test.rb script to make it better * Changed install instructions slightly ## 0.1.2 - 25-Aug-2002 * Slight change to preprocessor commands to avoid redefining CLK_TCK on those systems that define it in time.h * Added an INSTALL file ## 0.1.1 - 21-Jun-2002 * The CLK_TCK constant wasn't necessarily being set correctly, which could lead to some odd results. This has been fixed. ## 0.1.0 - 17-Jun-2002 * Initial release diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index d6c9af6..be02ec0 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,31 +1,31 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' spec.version = '0.7.5' spec.author = 'Daniel J. Berger' spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'spec/sys_uptime_spec.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] spec.add_development_dependency 'rspec', '~> 3.9' spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', - 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/ffi/CHANGES.rdoc', + 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/ffi/CHANGES.md', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
d23cb8186ebf28e5892fa580570f31d0586baadc
Bump version.
diff --git a/lib/sys/uptime.rb b/lib/sys/uptime.rb index 1be2352..3e9ff03 100644 --- a/lib/sys/uptime.rb +++ b/lib/sys/uptime.rb @@ -1,12 +1,12 @@ if File::ALT_SEPARATOR require_relative 'windows/sys/uptime' else require_relative 'unix/sys/uptime' end module Sys class Uptime # The version of the sys-uptime library - VERSION = '0.7.4'.freeze + VERSION = '0.7.5'.freeze end end diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index 2e95f04..160d69c 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,103 +1,103 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'rspec' require 'socket' describe Sys::Uptime do example "version is set to expected value" do - expect(Sys::Uptime::VERSION).to eql('0.7.4') + expect(Sys::Uptime::VERSION).to eql('0.7.5') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example "seconds method basic functionality" do expect(Sys::Uptime).to respond_to(:seconds) expect{ Sys::Uptime.seconds }.not_to raise_error end example "seconds method returns a plausible value" do expect(Sys::Uptime.seconds).to be_kind_of(Integer) expect(Sys::Uptime.seconds).to be > 300 end example "minutes method basic functionality" do expect(Sys::Uptime).to respond_to(:minutes) expect{ Sys::Uptime.minutes }.not_to raise_error end example "minutes method returns a plausible value" do expect(Sys::Uptime.minutes).to be_kind_of(Integer) expect(Sys::Uptime.minutes).to be > 5 end example "hours method basic functionality" do expect(Sys::Uptime).to respond_to(:hours) expect{ Sys::Uptime.hours }.not_to raise_error end example "hours method returns a plausible value" do expect(Sys::Uptime.hours).to be_kind_of(Integer) expect(Sys::Uptime.hours).to be > 0 end example "days method basic functionality" do expect(Sys::Uptime).to respond_to(:days) expect{ Sys::Uptime.days }.not_to raise_error end example "days method returns a plausible value" do expect(Sys::Uptime.days).to be_kind_of(Integer) expect(Sys::Uptime.days).to be >= 0 end example "uptime method basic functionality" do expect(Sys::Uptime).to respond_to(:uptime) expect{ Sys::Uptime.uptime }.not_to raise_error end example "uptime method returns a non-empty string" do expect(Sys::Uptime.uptime).to be_kind_of(String) expect(Sys::Uptime.uptime.empty?).to be(false) end example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) end example "uptime accepts a host name on Windows", :if => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(Socket.gethostname) }.not_to raise_error end example "dhms method basic functionality" do expect(Sys::Uptime).to respond_to(:dhms) expect{ Sys::Uptime.dhms }.not_to raise_error expect(Sys::Uptime.dhms).to be_kind_of(Array) end example "dhms method returns an array of four elements" do expect(Sys::Uptime.dhms).not_to be_empty expect(Sys::Uptime.dhms.length).to eql(4) end example "boot_time method basic functionality" do expect(Sys::Uptime).to respond_to(:boot_time) expect{ Sys::Uptime.boot_time }.not_to raise_error end example "boot_time method returns a Time object" do expect(Sys::Uptime.boot_time).to be_kind_of(Time) end example "Uptime class cannot be instantiated" do expect{ Sys::Uptime.new }.to raise_error(StandardError) end example "Ensure that ffi functions are private" do methods = Sys::Uptime.methods(false).map{ |e| e.to_s } expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
1c4b3d033e796c3e9b7841f1afc14ca759d995c4
Minor tweaks.
diff --git a/README.md b/README.md index 0dd8a4d..5e4368e 100644 --- a/README.md +++ b/README.md @@ -1,69 +1,69 @@ ## Description A Ruby interface for getting system uptime information. ## Prerequisites ffi 0.1.0 or later on Unixy platforms. ## Installation -gem install sys-uptime +`gem install sys-uptime` ## Synopsis ``` - require 'sys-uptime' - include Sys +require 'sys-uptime' +include Sys - # Get everything - p Uptime.uptime - p Uptime.dhms.join(', ') +# Get everything +p Uptime.uptime +p Uptime.dhms.join(', ') - # Get individual units - p Uptime.days - p Uptime.hours - p Uptime.minutes - p Uptime.seconds +# Get individual units +p Uptime.days +p Uptime.hours +p Uptime.minutes +p Uptime.seconds - # Get the boot time - p Uptime.boot_time +# Get the boot time +p Uptime.boot_time ``` ## Notes On MS Windows the +Uptime.uptime+ and +Uptime.boot_time+ methods optionally takes a host name as a single argument. The default is localhost. The current time, users and load average are not included in this library module, even though you may be used to seeing them with the command line version of +uptime+. ## Known Bugs None that I am aware of. Please log any bugs you find on the project website at https://github.com/djberg96/sys-uptime. ## Questions "Doesn't Struct::Tms do this?" - No. ## License Apache-2.0 ## Copyright Copyright 2002-2019, Daniel J. Berger All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Ruby itself. ## Warranty This library is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. ## Acknowledgements Andrea Fazzi for help with the FFI version. Mike Hall for help with the BSD side of things for the original C code. Ola Eriksson, whose source code I shamelessly plagiarized to get a better implementation for systems that have the utmpx.h header file for the original C code. ## Author Daniel J. Berger
djberg96/sys-uptime
d6d89e21cfee3009cdc4fd4737adb8aea2a9b89d
Switch to markdown.
diff --git a/CHANGES.rdoc b/CHANGES.md similarity index 91% rename from CHANGES.rdoc rename to CHANGES.md index 175289f..0cbdc4b 100644 --- a/CHANGES.rdoc +++ b/CHANGES.md @@ -1,181 +1,181 @@ -== 0.7.4 - 18-Mar-2020 +## 0.7.4 - 18-Mar-2020 * Added a LICENSE file as per the requirements of the Apache-2.0 license. -== 0.7.3 - 31-Dec-2019 +## 0.7.3 - 31-Dec-2019 * Attempting to call Sys::Uptime.new will now raise an error. I thought this was already the case, but apparently one of the tests was bad. * Added explicit .rdoc extensions to various text files so that github will display them nicely. * Switched from test-unit to rspec as the testing framework of choice. * Updated the gemspec to reflect the filename updates, as well as the added development dependency. -== 0.7.2 - 4-Nov-2018 +## 0.7.2 - 4-Nov-2018 * Added metadata to the gemspec. * The VERSION constant is now frozen. * Updated cert. -== 0.7.1 - 14-May-2016 +## 0.7.1 - 14-May-2016 * Altered internal layout, which also fixed a require bug. Thanks go to jkburges for the spot. * Moved the VERSION constant into a single file shared by all platforms. -== 0.7.0 - 3-Oct-2015 +## 0.7.0 - 3-Oct-2015 * Changed license to Apache 2.0. * Added a cert. This gem is now signed. * Added a sys-uptime.rb file for convenience. * Gem related tasks in the Rakefile now assume Rubygems 2.x. -== 0.6.2 - 8-Nov-2014 +## 0.6.2 - 8-Nov-2014 * Minor updates to gemspec and Rakefile. -== 0.6.1 - 22-Oct-2012 +## 0.6.1 - 22-Oct-2012 * Refactored a private method in the MS Windows source. * Minor fix for one private method test. * Fixed an RbConfig vs Config warning. Thanks Pedro Carrico. -== 0.6.0 - 11-Dec-2011 +## 0.6.0 - 11-Dec-2011 * Switched Unix code to use FFI. * Removed all of the C related tasks from the Rakefile and added the gem:build and gem:install tasks. * Internal directory layout changes, with appropriate changes to the gemspec. -== 0.5.3 - 7-May-2009 +## 0.5.3 - 7-May-2009 * Altered the Uptime.seconds implementation on Linux so that it works with both Ruby 1.8.x and 1.9.x. Thanks go to Alexey Chebotar for the spot. -== 0.5.2 - 13-Dec-2008 +## 0.5.2 - 13-Dec-2008 * Fixed a date/time issue in the Windows version caused by Ruby itself. * Fixed the Uptime.seconds, Uptime.minutes and Uptime.hours methods on MS Windows. * Renamed the test file to 'test_sys_uptime.rb'. * Some minor updates to the Rakefile. -== 0.5.1 - 26-Jul-2007 +## 0.5.1 - 26-Jul-2007 * Fixed bug in the MS Windows version caused by incorrect parsing of an MS specific date format (caused by a bug in Ruby 1.8.6). Thanks go to Robert H. for the spot. * Inlined the Rake installation tasks, so the install.rb file has been removed. * Added an 'install_gem' Rake task, and updated the README installation instructions. -== 0.5.0 - 30-Mar-2007 +## 0.5.0 - 30-Mar-2007 * For platforms that use C code, the code now always uses the sysctl() function if supported by your system. This replaces the platform specific checks I was doing for the various BSD flavors. * Fix for OS X - the Uptime.boot_time method now works. * UptimeError is now Uptime::Error. * Improved RDoc in the uptime.c source code. * Added a Rakefile - users should now use the 'test' and 'install' rake tasks. * Updates to the MANIFEST, README and uptime.txt files. -== 0.4.5 - 19-Nov-2006 +## 0.4.5 - 19-Nov-2006 * Internal layout changes, minor doc updates and gemspec improvements. * No code changes. -== 0.4.4 - 30-Jun-2006 +## 0.4.4 - 30-Jun-2006 * Added inline rdoc documentation to the source files. * Added a gemspec. -== 0.4.3 - 18-Dec-2005 +## 0.4.3 - 18-Dec-2005 * Changed the Linux version to pure Ruby. The current method of determining uptime in unix.c does not work in Linux kernel 2.6+. So, from now on it reads out of /proc/uptime. -== 0.4.2 - 6-May-2005 +## 0.4.2 - 6-May-2005 * Fixed a potential boot_time bug. * Removed the version.h file. It's no longer needed since the Windows version is pure Ruby. * NetBSD 2.x and FreeBSD 5.x now supported. * Removed the INSTALL file. Installation instructions are now in the README file. * Removed the uptime.rd file. You can generate html documentation by running rdoc over the uptime.txt file. * Made most documents rdoc friendly. * Moved project to RubyForge. -== 0.4.1 - 14-Dec-2004 +## 0.4.1 - 14-Dec-2004 * Moved freebsd code into unix.c file. * Should now work past 249 days (2**31) on systems that have utmpx.h. * Fixed a bug with regards to boot_time, where it was possible that it would simply be empty. -== 0.4.0 - 8-Jul-2004 +## 0.4.0 - 8-Jul-2004 * Removed all reference to the CLK_TCK constant, as per documentation from Richard Stevens that it is deprecated and that sysconf() should be used instead (well, I knew about this, but ignored it until now). * Scrapped the C version for Windows in favor of a pure Ruby version that uses win32ole + WMI. * Added a boot_time method for Unix systems (Windows already had this). * Added an UptimeError class on Unix systems (and replaced UptimeException on Windows). * Modified an internal function to raise an UptimeError if the times() function fails. Also, it now returns an unsigned long instead of a plain long. * Replaced the two different test suites with a single, unified test suite. * Cleaned up the extconf.rb script. I now assume that TestUnit is installed. * Removed the load_avg method (which was never advertised and which I hope you weren't using). You can find a load_avg method in the sys-cpu package. * Changed uptime.rd2 to uptime.rd to be consistent with my other packages. * Removed the uptime.html file - you may generate that on your own. * Added warranty and license info. -== 0.3.2 - 30-Dec-2003 +## 0.3.2 - 30-Dec-2003 * Cleaned up some warnings that showed up with -Wall on some unix platforms (int vs long format, explicit include) * Minor test suite and extconf.rb changes -== 0.3.1 - 25-Jun-2003 +## 0.3.1 - 25-Jun-2003 * Modified test files to handle HP-UX extensions * Minor doc updates * Added the dhms() method. Actually, this was in the 0.3.0 release, I just forgot to mention it in this file :) -== 0.3.0 - 22-Jun-2003 +## 0.3.0 - 22-Jun-2003 * Added OS X support - thanks go to Mike Hall for the patch * Fixed incorrect values in FreeBSD (again Mike Hall) * Modified tc_unix.rb test suite to handle OS X, along with a bit * of minor cleanup * Removed VERSION class method. Use the constant instead * Separated FreeBSD/OS X source into its own file (freebsd.c). The #ifdefs were starting to get too ugly for me -== 0.2.1 - 13-May-2003 +## 0.2.1 - 13-May-2003 * Fixed bug in extconf.rb file, and made some major changes * Modified test.rb for those without TestUnit * Modified TestUnit tests - some bogus tests were removed * Added a README file with some additional info * Created a version.h file, so that I can keep the VERSION number in one place * Docs automatically included in doc directory (i.e. no more interactive document creation) -== 0.2.0 - 13-Mar-2003 +## 0.2.0 - 13-Mar-2003 * Added MS Windows support * Added a VERSION constant * Added a test suite (for those with TestUnit installed) * Internal directory layout change * uptime.c is now split into unix.c and windows.c (and linked appropriately) * Changelog and Manifest are now CHANGES and MANIFEST, respectively * Many changes to extconf.rb -== 0.1.3 - 6-Jan-2003 +## 0.1.3 - 6-Jan-2003 * Added a VERSION class method * Added a copyright notice * Fixed up the docs a bit and moved them to the doc directory * Changed the tarball name to match the RAA package name * Modified test.rb script to make it better * Changed install instructions slightly -== 0.1.2 - 25-Aug-2002 +## 0.1.2 - 25-Aug-2002 * Slight change to preprocessor commands to avoid redefining CLK_TCK on those systems that define it in time.h * Added an INSTALL file -== 0.1.1 - 21-Jun-2002 +## 0.1.1 - 21-Jun-2002 * The CLK_TCK constant wasn't necessarily being set correctly, which could lead to some odd results. This has been fixed. -== 0.1.0 - 17-Jun-2002 +## 0.1.0 - 17-Jun-2002 * Initial release diff --git a/MANIFEST.rdoc b/MANIFEST.md similarity index 100% rename from MANIFEST.rdoc rename to MANIFEST.md diff --git a/README.rdoc b/README.md similarity index 89% rename from README.rdoc rename to README.md index 3a04cdf..0dd8a4d 100644 --- a/README.rdoc +++ b/README.md @@ -1,67 +1,69 @@ -== Description +## Description A Ruby interface for getting system uptime information. -== Prerequisites +## Prerequisites ffi 0.1.0 or later on Unixy platforms. -== Installation +## Installation gem install sys-uptime -== Synopsis +## Synopsis +``` require 'sys-uptime' include Sys # Get everything p Uptime.uptime p Uptime.dhms.join(', ') # Get individual units p Uptime.days p Uptime.hours p Uptime.minutes p Uptime.seconds # Get the boot time p Uptime.boot_time +``` -== Notes +## Notes On MS Windows the +Uptime.uptime+ and +Uptime.boot_time+ methods optionally takes a host name as a single argument. The default is localhost. The current time, users and load average are not included in this library module, even though you may be used to seeing them with the command line version of +uptime+. -== Known Bugs +## Known Bugs None that I am aware of. Please log any bugs you find on the project website at https://github.com/djberg96/sys-uptime. -== Questions +## Questions "Doesn't Struct::Tms do this?" - No. -== License +## License Apache-2.0 -== Copyright +## Copyright Copyright 2002-2019, Daniel J. Berger All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Ruby itself. -== Warranty +## Warranty This library is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. -== Acknowledgements +## Acknowledgements Andrea Fazzi for help with the FFI version. Mike Hall for help with the BSD side of things for the original C code. Ola Eriksson, whose source code I shamelessly plagiarized to get a better implementation for systems that have the utmpx.h header file for the original C code. -== Author +## Author Daniel J. Berger diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 597b181..d6c9af6 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,32 +1,31 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' spec.version = '0.7.5' spec.author = 'Daniel J. Berger' spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'spec/sys_uptime_spec.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] - spec.extra_rdoc_files = Dir["*.rdoc"] spec.add_development_dependency 'rspec', '~> 3.9' spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/ffi/CHANGES.rdoc', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
da0f6259c5fe5329c5949aecde9ac20b57060f17
Added changes for 0.7.4 that I forgot.
diff --git a/CHANGES.rdoc b/CHANGES.rdoc index 6b7eaec..175289f 100644 --- a/CHANGES.rdoc +++ b/CHANGES.rdoc @@ -1,178 +1,181 @@ +== 0.7.4 - 18-Mar-2020 +* Added a LICENSE file as per the requirements of the Apache-2.0 license. + == 0.7.3 - 31-Dec-2019 * Attempting to call Sys::Uptime.new will now raise an error. I thought this was already the case, but apparently one of the tests was bad. * Added explicit .rdoc extensions to various text files so that github will display them nicely. * Switched from test-unit to rspec as the testing framework of choice. * Updated the gemspec to reflect the filename updates, as well as the added development dependency. == 0.7.2 - 4-Nov-2018 * Added metadata to the gemspec. * The VERSION constant is now frozen. * Updated cert. == 0.7.1 - 14-May-2016 * Altered internal layout, which also fixed a require bug. Thanks go to jkburges for the spot. * Moved the VERSION constant into a single file shared by all platforms. == 0.7.0 - 3-Oct-2015 * Changed license to Apache 2.0. * Added a cert. This gem is now signed. * Added a sys-uptime.rb file for convenience. * Gem related tasks in the Rakefile now assume Rubygems 2.x. == 0.6.2 - 8-Nov-2014 * Minor updates to gemspec and Rakefile. == 0.6.1 - 22-Oct-2012 * Refactored a private method in the MS Windows source. * Minor fix for one private method test. * Fixed an RbConfig vs Config warning. Thanks Pedro Carrico. == 0.6.0 - 11-Dec-2011 * Switched Unix code to use FFI. * Removed all of the C related tasks from the Rakefile and added the gem:build and gem:install tasks. * Internal directory layout changes, with appropriate changes to the gemspec. == 0.5.3 - 7-May-2009 * Altered the Uptime.seconds implementation on Linux so that it works with both Ruby 1.8.x and 1.9.x. Thanks go to Alexey Chebotar for the spot. == 0.5.2 - 13-Dec-2008 * Fixed a date/time issue in the Windows version caused by Ruby itself. * Fixed the Uptime.seconds, Uptime.minutes and Uptime.hours methods on MS Windows. * Renamed the test file to 'test_sys_uptime.rb'. * Some minor updates to the Rakefile. == 0.5.1 - 26-Jul-2007 * Fixed bug in the MS Windows version caused by incorrect parsing of an MS specific date format (caused by a bug in Ruby 1.8.6). Thanks go to Robert H. for the spot. * Inlined the Rake installation tasks, so the install.rb file has been removed. * Added an 'install_gem' Rake task, and updated the README installation instructions. == 0.5.0 - 30-Mar-2007 * For platforms that use C code, the code now always uses the sysctl() function if supported by your system. This replaces the platform specific checks I was doing for the various BSD flavors. * Fix for OS X - the Uptime.boot_time method now works. * UptimeError is now Uptime::Error. * Improved RDoc in the uptime.c source code. * Added a Rakefile - users should now use the 'test' and 'install' rake tasks. * Updates to the MANIFEST, README and uptime.txt files. == 0.4.5 - 19-Nov-2006 * Internal layout changes, minor doc updates and gemspec improvements. * No code changes. == 0.4.4 - 30-Jun-2006 * Added inline rdoc documentation to the source files. * Added a gemspec. == 0.4.3 - 18-Dec-2005 * Changed the Linux version to pure Ruby. The current method of determining uptime in unix.c does not work in Linux kernel 2.6+. So, from now on it reads out of /proc/uptime. == 0.4.2 - 6-May-2005 * Fixed a potential boot_time bug. * Removed the version.h file. It's no longer needed since the Windows version is pure Ruby. * NetBSD 2.x and FreeBSD 5.x now supported. * Removed the INSTALL file. Installation instructions are now in the README file. * Removed the uptime.rd file. You can generate html documentation by running rdoc over the uptime.txt file. * Made most documents rdoc friendly. * Moved project to RubyForge. == 0.4.1 - 14-Dec-2004 * Moved freebsd code into unix.c file. * Should now work past 249 days (2**31) on systems that have utmpx.h. * Fixed a bug with regards to boot_time, where it was possible that it would simply be empty. == 0.4.0 - 8-Jul-2004 * Removed all reference to the CLK_TCK constant, as per documentation from Richard Stevens that it is deprecated and that sysconf() should be used instead (well, I knew about this, but ignored it until now). * Scrapped the C version for Windows in favor of a pure Ruby version that uses win32ole + WMI. * Added a boot_time method for Unix systems (Windows already had this). * Added an UptimeError class on Unix systems (and replaced UptimeException on Windows). * Modified an internal function to raise an UptimeError if the times() function fails. Also, it now returns an unsigned long instead of a plain long. * Replaced the two different test suites with a single, unified test suite. * Cleaned up the extconf.rb script. I now assume that TestUnit is installed. * Removed the load_avg method (which was never advertised and which I hope you weren't using). You can find a load_avg method in the sys-cpu package. * Changed uptime.rd2 to uptime.rd to be consistent with my other packages. * Removed the uptime.html file - you may generate that on your own. * Added warranty and license info. == 0.3.2 - 30-Dec-2003 * Cleaned up some warnings that showed up with -Wall on some unix platforms (int vs long format, explicit include) * Minor test suite and extconf.rb changes == 0.3.1 - 25-Jun-2003 * Modified test files to handle HP-UX extensions * Minor doc updates * Added the dhms() method. Actually, this was in the 0.3.0 release, I just forgot to mention it in this file :) == 0.3.0 - 22-Jun-2003 * Added OS X support - thanks go to Mike Hall for the patch * Fixed incorrect values in FreeBSD (again Mike Hall) * Modified tc_unix.rb test suite to handle OS X, along with a bit * of minor cleanup * Removed VERSION class method. Use the constant instead * Separated FreeBSD/OS X source into its own file (freebsd.c). The #ifdefs were starting to get too ugly for me == 0.2.1 - 13-May-2003 * Fixed bug in extconf.rb file, and made some major changes * Modified test.rb for those without TestUnit * Modified TestUnit tests - some bogus tests were removed * Added a README file with some additional info * Created a version.h file, so that I can keep the VERSION number in one place * Docs automatically included in doc directory (i.e. no more interactive document creation) == 0.2.0 - 13-Mar-2003 * Added MS Windows support * Added a VERSION constant * Added a test suite (for those with TestUnit installed) * Internal directory layout change * uptime.c is now split into unix.c and windows.c (and linked appropriately) * Changelog and Manifest are now CHANGES and MANIFEST, respectively * Many changes to extconf.rb == 0.1.3 - 6-Jan-2003 * Added a VERSION class method * Added a copyright notice * Fixed up the docs a bit and moved them to the doc directory * Changed the tarball name to match the RAA package name * Modified test.rb script to make it better * Changed install instructions slightly == 0.1.2 - 25-Aug-2002 * Slight change to preprocessor commands to avoid redefining CLK_TCK on those systems that define it in time.h * Added an INSTALL file == 0.1.1 - 21-Jun-2002 * The CLK_TCK constant wasn't necessarily being set correctly, which could lead to some odd results. This has been fixed. == 0.1.0 - 17-Jun-2002 * Initial release
djberg96/sys-uptime
79c104ddac390ec910f69dde7d02bf6d188e88d2
Add .lock to clean task.
diff --git a/Rakefile b/Rakefile index 425084e..aaaec03 100644 --- a/Rakefile +++ b/Rakefile @@ -1,34 +1,34 @@ require 'rake' require 'rake/clean' require 'rake/testtask' require 'rspec/core/rake_task' -CLEAN.include("**/*.gem", "**/*.rbx", "**/*.rbc") +CLEAN.include("**/*.gem", "**/*.rbx", "**/*.rbc", "**/*.lock") namespace 'gem' do desc 'Build the sys-uptime gem' task :create => [:clean] do require 'rubygems/package' spec = eval(IO.read('sys-uptime.gemspec')) spec.signing_key = File.join(Dir.home, '.ssh', 'gem-private_key.pem') if File::ALT_SEPARATOR spec.platform = Gem::Platform.new(['universal', 'mingw32']) else spec.add_dependency('ffi', '~> 1.1') end Gem::Package.build(spec) end desc 'Install the sys-uptime gem' task :install => [:create] do file = Dir["*.gem"].first sh "gem install -l #{file}" end end desc "Run the test suite" RSpec::Core::RakeTask.new(:spec) task :default => :spec
djberg96/sys-uptime
71a292dda1e6bdfe140e38175be1ee1d9593bd07
Fix require line.
diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index 5326ecc..2e95f04 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,103 +1,103 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' -require 'test-unit' +require 'rspec' require 'socket' describe Sys::Uptime do example "version is set to expected value" do expect(Sys::Uptime::VERSION).to eql('0.7.4') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example "seconds method basic functionality" do expect(Sys::Uptime).to respond_to(:seconds) expect{ Sys::Uptime.seconds }.not_to raise_error end example "seconds method returns a plausible value" do expect(Sys::Uptime.seconds).to be_kind_of(Integer) expect(Sys::Uptime.seconds).to be > 300 end example "minutes method basic functionality" do expect(Sys::Uptime).to respond_to(:minutes) expect{ Sys::Uptime.minutes }.not_to raise_error end example "minutes method returns a plausible value" do expect(Sys::Uptime.minutes).to be_kind_of(Integer) expect(Sys::Uptime.minutes).to be > 5 end example "hours method basic functionality" do expect(Sys::Uptime).to respond_to(:hours) expect{ Sys::Uptime.hours }.not_to raise_error end example "hours method returns a plausible value" do expect(Sys::Uptime.hours).to be_kind_of(Integer) expect(Sys::Uptime.hours).to be > 0 end example "days method basic functionality" do expect(Sys::Uptime).to respond_to(:days) expect{ Sys::Uptime.days }.not_to raise_error end example "days method returns a plausible value" do expect(Sys::Uptime.days).to be_kind_of(Integer) expect(Sys::Uptime.days).to be >= 0 end example "uptime method basic functionality" do expect(Sys::Uptime).to respond_to(:uptime) expect{ Sys::Uptime.uptime }.not_to raise_error end example "uptime method returns a non-empty string" do expect(Sys::Uptime.uptime).to be_kind_of(String) expect(Sys::Uptime.uptime.empty?).to be(false) end example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) end example "uptime accepts a host name on Windows", :if => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(Socket.gethostname) }.not_to raise_error end example "dhms method basic functionality" do expect(Sys::Uptime).to respond_to(:dhms) expect{ Sys::Uptime.dhms }.not_to raise_error expect(Sys::Uptime.dhms).to be_kind_of(Array) end example "dhms method returns an array of four elements" do expect(Sys::Uptime.dhms).not_to be_empty expect(Sys::Uptime.dhms.length).to eql(4) end example "boot_time method basic functionality" do expect(Sys::Uptime).to respond_to(:boot_time) expect{ Sys::Uptime.boot_time }.not_to raise_error end example "boot_time method returns a Time object" do expect(Sys::Uptime.boot_time).to be_kind_of(Time) end example "Uptime class cannot be instantiated" do expect{ Sys::Uptime.new }.to raise_error(StandardError) end example "Ensure that ffi functions are private" do methods = Sys::Uptime.methods(false).map{ |e| e.to_s } expect(methods).not_to include('time', 'times') end end
djberg96/sys-uptime
916dda3c26022d28572cbca0f0a3b29cd1c05fe4
Add gemfile.
diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..66fc744 --- /dev/null +++ b/Gemfile @@ -0,0 +1,11 @@ +source 'https://rubygems.org' do + gem 'rake' + + platforms :ruby do + gem 'ffi', '~> 1.1' + end + + group 'test' do + gem 'rspec', '~> 3.9' + end +end diff --git a/Rakefile b/Rakefile index 4eae015..425084e 100644 --- a/Rakefile +++ b/Rakefile @@ -1,34 +1,34 @@ require 'rake' require 'rake/clean' require 'rake/testtask' require 'rspec/core/rake_task' CLEAN.include("**/*.gem", "**/*.rbx", "**/*.rbc") namespace 'gem' do desc 'Build the sys-uptime gem' task :create => [:clean] do require 'rubygems/package' spec = eval(IO.read('sys-uptime.gemspec')) spec.signing_key = File.join(Dir.home, '.ssh', 'gem-private_key.pem') if File::ALT_SEPARATOR - spec.platform = Gem::Platform.new(['universal','mingw32']) + spec.platform = Gem::Platform.new(['universal', 'mingw32']) else - spec.add_dependency('ffi', '>= 1.0.0') + spec.add_dependency('ffi', '~> 1.1') end - Gem::Package.build(spec, true) + Gem::Package.build(spec) end desc 'Install the sys-uptime gem' task :install => [:create] do file = Dir["*.gem"].first sh "gem install -l #{file}" end end desc "Run the test suite" RSpec::Core::RakeTask.new(:spec) task :default => :spec diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 68c12c4..597b181 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,32 +1,32 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' - spec.version = '0.7.4' + spec.version = '0.7.5' spec.author = 'Daniel J. Berger' spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'spec/sys_uptime_spec.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] spec.extra_rdoc_files = Dir["*.rdoc"] - spec.add_development_dependency 'rspec', '~> 3' + spec.add_development_dependency 'rspec', '~> 3.9' spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/ffi/CHANGES.rdoc', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
1d77367d7b95526566b9833ddb48782136a76e42
Add LICENSE file.
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/MANIFEST.rdoc b/MANIFEST.rdoc index e35a881..5662820 100644 --- a/MANIFEST.rdoc +++ b/MANIFEST.rdoc @@ -1,11 +1,12 @@ * CHANGES.rdoc +* LICENSE * MANIFEST.rdoc * Rakefile * README.rdoc * sys-uptime.gemspec * certs/djberg96_pub.pem * examples/test.rb * lib/sys-uptime.rb * lib/unix/sys/uptime.rb * lib/windows/sys/uptime.rb * spec/sys_uptime_spec.rb diff --git a/lib/sys/uptime.rb b/lib/sys/uptime.rb index b8e6161..1be2352 100644 --- a/lib/sys/uptime.rb +++ b/lib/sys/uptime.rb @@ -1,12 +1,12 @@ if File::ALT_SEPARATOR require_relative 'windows/sys/uptime' else require_relative 'unix/sys/uptime' end module Sys class Uptime # The version of the sys-uptime library - VERSION = '0.7.3'.freeze + VERSION = '0.7.4'.freeze end end diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index d5c2ce2..5326ecc 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,103 +1,103 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'test-unit' require 'socket' describe Sys::Uptime do example "version is set to expected value" do - expect(Sys::Uptime::VERSION).to eql('0.7.3') + expect(Sys::Uptime::VERSION).to eql('0.7.4') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example "seconds method basic functionality" do expect(Sys::Uptime).to respond_to(:seconds) expect{ Sys::Uptime.seconds }.not_to raise_error end example "seconds method returns a plausible value" do expect(Sys::Uptime.seconds).to be_kind_of(Integer) expect(Sys::Uptime.seconds).to be > 300 end example "minutes method basic functionality" do expect(Sys::Uptime).to respond_to(:minutes) expect{ Sys::Uptime.minutes }.not_to raise_error end example "minutes method returns a plausible value" do expect(Sys::Uptime.minutes).to be_kind_of(Integer) expect(Sys::Uptime.minutes).to be > 5 end example "hours method basic functionality" do expect(Sys::Uptime).to respond_to(:hours) expect{ Sys::Uptime.hours }.not_to raise_error end example "hours method returns a plausible value" do expect(Sys::Uptime.hours).to be_kind_of(Integer) expect(Sys::Uptime.hours).to be > 0 end example "days method basic functionality" do expect(Sys::Uptime).to respond_to(:days) expect{ Sys::Uptime.days }.not_to raise_error end example "days method returns a plausible value" do expect(Sys::Uptime.days).to be_kind_of(Integer) expect(Sys::Uptime.days).to be >= 0 end example "uptime method basic functionality" do expect(Sys::Uptime).to respond_to(:uptime) expect{ Sys::Uptime.uptime }.not_to raise_error end example "uptime method returns a non-empty string" do expect(Sys::Uptime.uptime).to be_kind_of(String) expect(Sys::Uptime.uptime.empty?).to be(false) end example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) end example "uptime accepts a host name on Windows", :if => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(Socket.gethostname) }.not_to raise_error end example "dhms method basic functionality" do expect(Sys::Uptime).to respond_to(:dhms) expect{ Sys::Uptime.dhms }.not_to raise_error expect(Sys::Uptime.dhms).to be_kind_of(Array) end example "dhms method returns an array of four elements" do expect(Sys::Uptime.dhms).not_to be_empty expect(Sys::Uptime.dhms.length).to eql(4) end example "boot_time method basic functionality" do expect(Sys::Uptime).to respond_to(:boot_time) expect{ Sys::Uptime.boot_time }.not_to raise_error end example "boot_time method returns a Time object" do expect(Sys::Uptime.boot_time).to be_kind_of(Time) end example "Uptime class cannot be instantiated" do expect{ Sys::Uptime.new }.to raise_error(StandardError) end example "Ensure that ffi functions are private" do methods = Sys::Uptime.methods(false).map{ |e| e.to_s } expect(methods).not_to include('time', 'times') end end diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 4e0b99b..32a59ba 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,32 +1,32 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' - spec.version = '0.7.3' + spec.version = '0.7.4' spec.author = 'Daniel J. Berger' spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'spec/sys_uptime_spec.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] spec.extra_rdoc_files = Dir["*.rdoc"] spec.add_development_dependency 'rspec', '~> 3' spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/ffi/CHANGES', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
f20b0d87e2d1f18c75bd7920c6a1d18d6c8f6c36
Added changes for 0.7.3.
diff --git a/CHANGES.rdoc b/CHANGES.rdoc index 852aa87..6b7eaec 100644 --- a/CHANGES.rdoc +++ b/CHANGES.rdoc @@ -1,169 +1,178 @@ +== 0.7.3 - 31-Dec-2019 +* Attempting to call Sys::Uptime.new will now raise an error. I thought + this was already the case, but apparently one of the tests was bad. +* Added explicit .rdoc extensions to various text files so that github + will display them nicely. +* Switched from test-unit to rspec as the testing framework of choice. +* Updated the gemspec to reflect the filename updates, as well as the + added development dependency. + == 0.7.2 - 4-Nov-2018 * Added metadata to the gemspec. * The VERSION constant is now frozen. * Updated cert. == 0.7.1 - 14-May-2016 * Altered internal layout, which also fixed a require bug. Thanks go to jkburges for the spot. * Moved the VERSION constant into a single file shared by all platforms. == 0.7.0 - 3-Oct-2015 * Changed license to Apache 2.0. * Added a cert. This gem is now signed. * Added a sys-uptime.rb file for convenience. * Gem related tasks in the Rakefile now assume Rubygems 2.x. == 0.6.2 - 8-Nov-2014 * Minor updates to gemspec and Rakefile. == 0.6.1 - 22-Oct-2012 * Refactored a private method in the MS Windows source. * Minor fix for one private method test. * Fixed an RbConfig vs Config warning. Thanks Pedro Carrico. == 0.6.0 - 11-Dec-2011 * Switched Unix code to use FFI. * Removed all of the C related tasks from the Rakefile and added the gem:build and gem:install tasks. * Internal directory layout changes, with appropriate changes to the gemspec. == 0.5.3 - 7-May-2009 * Altered the Uptime.seconds implementation on Linux so that it works with both Ruby 1.8.x and 1.9.x. Thanks go to Alexey Chebotar for the spot. == 0.5.2 - 13-Dec-2008 * Fixed a date/time issue in the Windows version caused by Ruby itself. * Fixed the Uptime.seconds, Uptime.minutes and Uptime.hours methods on MS Windows. * Renamed the test file to 'test_sys_uptime.rb'. * Some minor updates to the Rakefile. == 0.5.1 - 26-Jul-2007 * Fixed bug in the MS Windows version caused by incorrect parsing of an MS specific date format (caused by a bug in Ruby 1.8.6). Thanks go to Robert H. for the spot. * Inlined the Rake installation tasks, so the install.rb file has been removed. * Added an 'install_gem' Rake task, and updated the README installation instructions. == 0.5.0 - 30-Mar-2007 * For platforms that use C code, the code now always uses the sysctl() function if supported by your system. This replaces the platform specific checks I was doing for the various BSD flavors. * Fix for OS X - the Uptime.boot_time method now works. * UptimeError is now Uptime::Error. * Improved RDoc in the uptime.c source code. * Added a Rakefile - users should now use the 'test' and 'install' rake tasks. * Updates to the MANIFEST, README and uptime.txt files. == 0.4.5 - 19-Nov-2006 * Internal layout changes, minor doc updates and gemspec improvements. * No code changes. == 0.4.4 - 30-Jun-2006 * Added inline rdoc documentation to the source files. * Added a gemspec. == 0.4.3 - 18-Dec-2005 * Changed the Linux version to pure Ruby. The current method of determining uptime in unix.c does not work in Linux kernel 2.6+. So, from now on it reads out of /proc/uptime. == 0.4.2 - 6-May-2005 * Fixed a potential boot_time bug. * Removed the version.h file. It's no longer needed since the Windows version is pure Ruby. * NetBSD 2.x and FreeBSD 5.x now supported. * Removed the INSTALL file. Installation instructions are now in the README file. * Removed the uptime.rd file. You can generate html documentation by running rdoc over the uptime.txt file. * Made most documents rdoc friendly. * Moved project to RubyForge. == 0.4.1 - 14-Dec-2004 * Moved freebsd code into unix.c file. * Should now work past 249 days (2**31) on systems that have utmpx.h. * Fixed a bug with regards to boot_time, where it was possible that it would simply be empty. == 0.4.0 - 8-Jul-2004 * Removed all reference to the CLK_TCK constant, as per documentation from Richard Stevens that it is deprecated and that sysconf() should be used instead (well, I knew about this, but ignored it until now). * Scrapped the C version for Windows in favor of a pure Ruby version that uses win32ole + WMI. * Added a boot_time method for Unix systems (Windows already had this). * Added an UptimeError class on Unix systems (and replaced UptimeException on Windows). * Modified an internal function to raise an UptimeError if the times() function fails. Also, it now returns an unsigned long instead of a plain long. * Replaced the two different test suites with a single, unified test suite. * Cleaned up the extconf.rb script. I now assume that TestUnit is installed. * Removed the load_avg method (which was never advertised and which I hope you weren't using). You can find a load_avg method in the sys-cpu package. * Changed uptime.rd2 to uptime.rd to be consistent with my other packages. * Removed the uptime.html file - you may generate that on your own. * Added warranty and license info. == 0.3.2 - 30-Dec-2003 * Cleaned up some warnings that showed up with -Wall on some unix platforms (int vs long format, explicit include) * Minor test suite and extconf.rb changes == 0.3.1 - 25-Jun-2003 * Modified test files to handle HP-UX extensions * Minor doc updates * Added the dhms() method. Actually, this was in the 0.3.0 release, I just forgot to mention it in this file :) == 0.3.0 - 22-Jun-2003 * Added OS X support - thanks go to Mike Hall for the patch * Fixed incorrect values in FreeBSD (again Mike Hall) * Modified tc_unix.rb test suite to handle OS X, along with a bit * of minor cleanup * Removed VERSION class method. Use the constant instead * Separated FreeBSD/OS X source into its own file (freebsd.c). The #ifdefs were starting to get too ugly for me == 0.2.1 - 13-May-2003 * Fixed bug in extconf.rb file, and made some major changes * Modified test.rb for those without TestUnit * Modified TestUnit tests - some bogus tests were removed * Added a README file with some additional info * Created a version.h file, so that I can keep the VERSION number in one place * Docs automatically included in doc directory (i.e. no more interactive document creation) == 0.2.0 - 13-Mar-2003 * Added MS Windows support * Added a VERSION constant * Added a test suite (for those with TestUnit installed) * Internal directory layout change * uptime.c is now split into unix.c and windows.c (and linked appropriately) * Changelog and Manifest are now CHANGES and MANIFEST, respectively * Many changes to extconf.rb == 0.1.3 - 6-Jan-2003 * Added a VERSION class method * Added a copyright notice * Fixed up the docs a bit and moved them to the doc directory * Changed the tarball name to match the RAA package name * Modified test.rb script to make it better * Changed install instructions slightly == 0.1.2 - 25-Aug-2002 * Slight change to preprocessor commands to avoid redefining CLK_TCK on those systems that define it in time.h * Added an INSTALL file == 0.1.1 - 21-Jun-2002 * The CLK_TCK constant wasn't necessarily being set correctly, which could lead to some odd results. This has been fixed. == 0.1.0 - 17-Jun-2002 * Initial release
djberg96/sys-uptime
925e4f68f6373f992267f4666d44165ca52f64f8
Make new a private class method.
diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index 7eb627a..501876b 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,144 +1,147 @@ require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end + # You cannot instantiate an instance of Sys::Uptime. + private_class_method :new + # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => e raise Error, e else query = "select LastBootupTime from Win32_OperatingSystem" results = wmi.ExecQuery(query) results.each{ |ole| time_array = parse_ms_date(ole.LastBootupTime) return Time.mktime(*time_array) } end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # def self.hours(host=Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # def self.minutes(host=Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # def self.seconds(host=Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? return Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) (Time.now - boot_time).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
77f0fd468dc9c0b3410cf103f3176894db10cdb5
Bump version.
diff --git a/lib/sys/uptime.rb b/lib/sys/uptime.rb index 1e92e0c..b8e6161 100644 --- a/lib/sys/uptime.rb +++ b/lib/sys/uptime.rb @@ -1,12 +1,12 @@ if File::ALT_SEPARATOR require_relative 'windows/sys/uptime' else require_relative 'unix/sys/uptime' end module Sys class Uptime # The version of the sys-uptime library - VERSION = '0.7.2'.freeze + VERSION = '0.7.3'.freeze end end
djberg96/sys-uptime
e8f09814d174651f5a397dc2807ce8b929327b72
Finish switch to rspec, make new a private method.
diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index 72ef553..87051b9 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,210 +1,210 @@ require 'ffi' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end private # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t - private_class_method :strerror, :sysconf, :time, :times + private_class_method :strerror, :sysconf, :time, :times, :new begin attach_function :sysctl, [:pointer, :uint, :pointer, :pointer, :pointer, :size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end public # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i Time.now - self.seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i begin IO.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 secs -= days * 86400 hours = secs / 3600 secs -= hours * 3600 mins = secs / 60 secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb index cd69ec5..7d336be 100644 --- a/spec/sys_uptime_spec.rb +++ b/spec/sys_uptime_spec.rb @@ -1,107 +1,103 @@ ##################################################################### # sys_uptime_spec.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'test-unit' require 'socket' describe Sys::Uptime do example "version is set to expected value" do expect(Sys::Uptime::VERSION).to eql('0.7.2') expect(Sys::Uptime::VERSION.frozen?).to be(true) end example "seconds method basic functionality" do expect(Sys::Uptime).to respond_to(:seconds) expect{ Sys::Uptime.seconds }.not_to raise_error end example "seconds method returns a plausible value" do expect(Sys::Uptime.seconds).to be_kind_of(Integer) expect(Sys::Uptime.seconds).to be > 300 end example "minutes method basic functionality" do expect(Sys::Uptime).to respond_to(:minutes) expect{ Sys::Uptime.minutes }.not_to raise_error end example "minutes method returns a plausible value" do expect(Sys::Uptime.minutes).to be_kind_of(Integer) expect(Sys::Uptime.minutes).to be > 5 end example "hours method basic functionality" do expect(Sys::Uptime).to respond_to(:hours) expect{ Sys::Uptime.hours }.not_to raise_error end example "hours method returns a plausible value" do expect(Sys::Uptime.hours).to be_kind_of(Integer) expect(Sys::Uptime.hours).to be > 0 end example "days method basic functionality" do expect(Sys::Uptime).to respond_to(:days) expect{ Sys::Uptime.days }.not_to raise_error end example "days method returns a plausible value" do expect(Sys::Uptime.days).to be_kind_of(Integer) expect(Sys::Uptime.days).to be >= 0 end example "uptime method basic functionality" do expect(Sys::Uptime).to respond_to(:uptime) expect{ Sys::Uptime.uptime }.not_to raise_error end example "uptime method returns a non-empty string" do expect(Sys::Uptime.uptime).to be_kind_of(String) expect(Sys::Uptime.uptime.empty?).to be(false) end example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) end -=begin - example "uptime accepts a host name on Windows" do - omit_unless(File::ALT_SEPARATOR, "MS Windows only") - assert_nothing_raised{ Uptime.uptime(Socket.gethostname) } + example "uptime accepts a host name on Windows", :if => File::ALT_SEPARATOR do + expect{ Sys::Uptime.uptime(Socket.gethostname) }.not_to raise_error end example "dhms method basic functionality" do - assert_respond_to(Uptime, :dhms) - assert_nothing_raised{ Uptime.dhms } - assert_kind_of(Array, Uptime.dhms) + expect(Sys::Uptime).to respond_to(:dhms) + expect{ Sys::Uptime.dhms }.not_to raise_error + expect(Sys::Uptime.dhms).to be_kind_of(Array) end example "dhms method returns an array of four elements" do - assert_false(Uptime.dhms.empty?) - assert_equal(4, Uptime.dhms.length) + expect(Sys::Uptime.dhms).not_to be_empty + expect(Sys::Uptime.dhms.length).to eql(4) end example "boot_time method basic functionality" do - assert_respond_to(Uptime, :boot_time) - assert_nothing_raised{ Uptime.boot_time } + expect(Sys::Uptime).to respond_to(:boot_time) + expect{ Sys::Uptime.boot_time }.not_to raise_error end example "boot_time method returns a Time object" do - assert_kind_of(Time, Uptime.boot_time) + expect(Sys::Uptime.boot_time).to be_kind_of(Time) end example "Uptime class cannot be instantiated" do - assert_kind_of(StandardError, Uptime::Error.new) + expect{ Sys::Uptime.new }.to raise_error(StandardError) end example "Ensure that ffi functions are private" do - methods = Uptime.methods(false).map{ |e| e.to_s } - assert_false(methods.include?('time')) - assert_false(methods.include?('times')) + methods = Sys::Uptime.methods(false).map{ |e| e.to_s } + expect(methods).not_to include('time', 'times') end -=end end
djberg96/sys-uptime
aac4c0010f6ff0296caeb480890d0bc125d5da5c
Convert tests to rspec.
diff --git a/Rakefile b/Rakefile index b44d076..4eae015 100644 --- a/Rakefile +++ b/Rakefile @@ -1,42 +1,34 @@ require 'rake' require 'rake/clean' require 'rake/testtask' +require 'rspec/core/rake_task' CLEAN.include("**/*.gem", "**/*.rbx", "**/*.rbc") namespace 'gem' do desc 'Build the sys-uptime gem' task :create => [:clean] do require 'rubygems/package' spec = eval(IO.read('sys-uptime.gemspec')) spec.signing_key = File.join(Dir.home, '.ssh', 'gem-private_key.pem') if File::ALT_SEPARATOR spec.platform = Gem::Platform.new(['universal','mingw32']) else spec.add_dependency('ffi', '>= 1.0.0') end Gem::Package.build(spec, true) end desc 'Install the sys-uptime gem' task :install => [:create] do file = Dir["*.gem"].first sh "gem install -l #{file}" end end desc "Run the test suite" -Rake::TestTask.new do |t| - if File::ALT_SEPARATOR - t.libs << 'lib/windows' - else - t.libs << 'lib/unix' - end - - t.warning = true - t.verbose = true -end +RSpec::Core::RakeTask.new(:spec) -task :default => :test +task :default => :spec diff --git a/spec/sys_uptime_spec.rb b/spec/sys_uptime_spec.rb new file mode 100644 index 0000000..cd69ec5 --- /dev/null +++ b/spec/sys_uptime_spec.rb @@ -0,0 +1,107 @@ +##################################################################### +# sys_uptime_spec.rb +# +# Test suite for sys-uptime. This should generally be run via the +# 'rake test' task, since it handles the pre-setup code for you. +##################################################################### +require 'sys/uptime' +require 'test-unit' +require 'socket' + +describe Sys::Uptime do + example "version is set to expected value" do + expect(Sys::Uptime::VERSION).to eql('0.7.2') + expect(Sys::Uptime::VERSION.frozen?).to be(true) + end + + example "seconds method basic functionality" do + expect(Sys::Uptime).to respond_to(:seconds) + expect{ Sys::Uptime.seconds }.not_to raise_error + end + + example "seconds method returns a plausible value" do + expect(Sys::Uptime.seconds).to be_kind_of(Integer) + expect(Sys::Uptime.seconds).to be > 300 + end + + example "minutes method basic functionality" do + expect(Sys::Uptime).to respond_to(:minutes) + expect{ Sys::Uptime.minutes }.not_to raise_error + end + + example "minutes method returns a plausible value" do + expect(Sys::Uptime.minutes).to be_kind_of(Integer) + expect(Sys::Uptime.minutes).to be > 5 + end + + example "hours method basic functionality" do + expect(Sys::Uptime).to respond_to(:hours) + expect{ Sys::Uptime.hours }.not_to raise_error + end + + example "hours method returns a plausible value" do + expect(Sys::Uptime.hours).to be_kind_of(Integer) + expect(Sys::Uptime.hours).to be > 0 + end + + example "days method basic functionality" do + expect(Sys::Uptime).to respond_to(:days) + expect{ Sys::Uptime.days }.not_to raise_error + end + + example "days method returns a plausible value" do + expect(Sys::Uptime.days).to be_kind_of(Integer) + expect(Sys::Uptime.days).to be >= 0 + end + + example "uptime method basic functionality" do + expect(Sys::Uptime).to respond_to(:uptime) + expect{ Sys::Uptime.uptime }.not_to raise_error + end + + example "uptime method returns a non-empty string" do + expect(Sys::Uptime.uptime).to be_kind_of(String) + expect(Sys::Uptime.uptime.empty?).to be(false) + end + + example "uptime method does not accept any arguments", :unless => File::ALT_SEPARATOR do + expect{ Sys::Uptime.uptime(1) }.to raise_error(ArgumentError) + end + +=begin + example "uptime accepts a host name on Windows" do + omit_unless(File::ALT_SEPARATOR, "MS Windows only") + assert_nothing_raised{ Uptime.uptime(Socket.gethostname) } + end + + example "dhms method basic functionality" do + assert_respond_to(Uptime, :dhms) + assert_nothing_raised{ Uptime.dhms } + assert_kind_of(Array, Uptime.dhms) + end + + example "dhms method returns an array of four elements" do + assert_false(Uptime.dhms.empty?) + assert_equal(4, Uptime.dhms.length) + end + + example "boot_time method basic functionality" do + assert_respond_to(Uptime, :boot_time) + assert_nothing_raised{ Uptime.boot_time } + end + + example "boot_time method returns a Time object" do + assert_kind_of(Time, Uptime.boot_time) + end + + example "Uptime class cannot be instantiated" do + assert_kind_of(StandardError, Uptime::Error.new) + end + + example "Ensure that ffi functions are private" do + methods = Uptime.methods(false).map{ |e| e.to_s } + assert_false(methods.include?('time')) + assert_false(methods.include?('times')) + end +=end +end diff --git a/test/test_sys_uptime.rb b/test/test_sys_uptime.rb deleted file mode 100644 index c058150..0000000 --- a/test/test_sys_uptime.rb +++ /dev/null @@ -1,107 +0,0 @@ -##################################################################### -# test_sys_uptime.rb -# -# Test suite for sys-uptime. This should generally be run via the -# 'rake test' task, since it handles the pre-setup code for you. -##################################################################### -require 'sys/uptime' -require 'test-unit' -require 'socket' -include Sys - -class TC_Sys_Uptime < Test::Unit::TestCase - test "version is set to expected value" do - assert_equal('0.7.2', Uptime::VERSION) - assert_true(Uptime::VERSION.frozen?) - end - - test "seconds method basic functionality" do - assert_respond_to(Uptime, :seconds) - assert_nothing_raised{ Uptime.seconds } - end - - test "seconds method returns a plausible value" do - assert_kind_of(Integer, Uptime.seconds) - assert_true(Uptime.seconds > 300) - end - - test "minutes method basic functionality" do - assert_respond_to(Uptime, :minutes) - assert_nothing_raised{ Uptime.minutes } - end - - test "minutes method returns a plausible value" do - assert_kind_of(Integer, Uptime.minutes) - assert_true(Uptime.minutes > 5) - end - - test "hours method basic functionality" do - assert_respond_to(Uptime, :hours) - assert_nothing_raised{ Uptime.hours } - end - - test "hours method returns a plausible value" do - assert_kind_of(Integer, Uptime.hours) - assert_true(Uptime.hours > 0) - end - - test "days method basic functionality" do - assert_respond_to(Uptime, :days) - assert_nothing_raised{ Uptime.days } - end - - test "days method returns a plausible value" do - assert_kind_of(Integer, Uptime.days) - assert_true(Uptime.days >= 0) - end - - test "uptime method basic functionality" do - assert_respond_to(Uptime, :uptime) - assert_nothing_raised{ Uptime.uptime } - end - - test "uptime method returns a non-empty string" do - assert_kind_of(String, Uptime.uptime) - assert_false(Uptime.uptime.empty?) - end - - test "uptime method does not accept any arguments" do - omit_if(File::ALT_SEPARATOR) - assert_raise(ArgumentError){ Uptime.uptime(1) } - end - - test "uptime accepts a host name on Windows" do - omit_unless(File::ALT_SEPARATOR, "MS Windows only") - assert_nothing_raised{ Uptime.uptime(Socket.gethostname) } - end - - test "dhms method basic functionality" do - assert_respond_to(Uptime, :dhms) - assert_nothing_raised{ Uptime.dhms } - assert_kind_of(Array, Uptime.dhms) - end - - test "dhms method returns an array of four elements" do - assert_false(Uptime.dhms.empty?) - assert_equal(4, Uptime.dhms.length) - end - - test "boot_time method basic functionality" do - assert_respond_to(Uptime, :boot_time) - assert_nothing_raised{ Uptime.boot_time } - end - - test "boot_time method returns a Time object" do - assert_kind_of(Time, Uptime.boot_time) - end - - test "Uptime class cannot be instantiated" do - assert_kind_of(StandardError, Uptime::Error.new) - end - - test "Ensure that ffi functions are private" do - methods = Uptime.methods(false).map{ |e| e.to_s } - assert_false(methods.include?('time')) - assert_false(methods.include?('times')) - end -end
djberg96/sys-uptime
d669bbf60d6dd2538b8f153a6d75f391be4b50b2
Formatting.
diff --git a/README.rdoc b/README.rdoc index cbb1a6a..3a04cdf 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,67 +1,67 @@ == Description A Ruby interface for getting system uptime information. == Prerequisites ffi 0.1.0 or later on Unixy platforms. == Installation gem install sys-uptime == Synopsis require 'sys-uptime' include Sys # Get everything p Uptime.uptime p Uptime.dhms.join(', ') # Get individual units p Uptime.days p Uptime.hours p Uptime.minutes p Uptime.seconds # Get the boot time p Uptime.boot_time == Notes -On MS Windows the Uptime.uptime and Uptime.boot_time methods optionally +On MS Windows the +Uptime.uptime+ and +Uptime.boot_time+ methods optionally takes a host name as a single argument. The default is localhost. The current time, users and load average are not included in this library module, even though you may be used to seeing them with the command -line version of 'uptime'. +line version of +uptime+. == Known Bugs None that I am aware of. Please log any bugs you find on the project website at https://github.com/djberg96/sys-uptime. == Questions "Doesn't Struct::Tms do this?" - No. == License Apache-2.0 == Copyright Copyright 2002-2019, Daniel J. Berger All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Ruby itself. == Warranty This library is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. == Acknowledgements Andrea Fazzi for help with the FFI version. Mike Hall for help with the BSD side of things for the original C code. Ola Eriksson, whose source code I shamelessly plagiarized to get a better implementation for systems that have the utmpx.h header file for the original C code. == Author Daniel J. Berger
djberg96/sys-uptime
d89f59e79fb7c54dc13ba8623de4bd8ef84961d9
Formatting.
diff --git a/README.rdoc b/README.rdoc index 402c5ef..cbb1a6a 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,66 +1,67 @@ -= Description - A Ruby interface for getting system uptime information. +== Description +A Ruby interface for getting system uptime information. -= Prerequisites - ffi 0.1.0 or later on Unixy platforms. +== Prerequisites +ffi 0.1.0 or later on Unixy platforms. -= Installation - gem install sys-uptime +== Installation -= Synopsis +gem install sys-uptime + +== Synopsis require 'sys-uptime' include Sys # Get everything p Uptime.uptime p Uptime.dhms.join(', ') # Get individual units p Uptime.days p Uptime.hours p Uptime.minutes p Uptime.seconds # Get the boot time p Uptime.boot_time -= Notes - On MS Windows the Uptime.uptime and Uptime.boot_time methods optionally - takes a host name as a single argument. The default is localhost. +== Notes +On MS Windows the Uptime.uptime and Uptime.boot_time methods optionally +takes a host name as a single argument. The default is localhost. - The current time, users and load average are not included in this library - module, even though you may be used to seeing them with the command - line version of 'uptime'. +The current time, users and load average are not included in this library +module, even though you may be used to seeing them with the command +line version of 'uptime'. == Known Bugs - None that I am aware of. Please log any bugs you find on the project - website at https://github.com/djberg96/sys-uptime. +None that I am aware of. Please log any bugs you find on the project +website at https://github.com/djberg96/sys-uptime. == Questions - "Doesn't Struct::Tms do this?" - No. +"Doesn't Struct::Tms do this?" - No. == License - Apache-2.0 +Apache-2.0 == Copyright - Copyright 2002-2019, Daniel J. Berger +Copyright 2002-2019, Daniel J. Berger - All Rights Reserved. This module is free software. It may be used, - redistributed and/or modified under the same terms as Ruby itself. +All Rights Reserved. This module is free software. It may be used, +redistributed and/or modified under the same terms as Ruby itself. == Warranty - This library is provided "as is" and without any express or - implied warranties, including, without limitation, the implied - warranties of merchantability and fitness for a particular purpose. +This library is provided "as is" and without any express or +implied warranties, including, without limitation, the implied +warranties of merchantability and fitness for a particular purpose. == Acknowledgements - Andrea Fazzi for help with the FFI version. +Andrea Fazzi for help with the FFI version. - Mike Hall for help with the BSD side of things for the original C code. +Mike Hall for help with the BSD side of things for the original C code. - Ola Eriksson, whose source code I shamelessly plagiarized to get a better - implementation for systems that have the utmpx.h header file for the - original C code. +Ola Eriksson, whose source code I shamelessly plagiarized to get a better +implementation for systems that have the utmpx.h header file for the +original C code. == Author - Daniel J. Berger +Daniel J. Berger
djberg96/sys-uptime
5d6aa01548db6d2a4f4572a01dcad74ceb611aad
Minor typo fix and formatting.
diff --git a/README b/README index 1ab30f1..402c5ef 100644 --- a/README +++ b/README @@ -1,66 +1,66 @@ = Description A Ruby interface for getting system uptime information. = Prerequisites ffi 0.1.0 or later on Unixy platforms. = Installation gem install sys-uptime = Synopsis require 'sys-uptime' include Sys # Get everything p Uptime.uptime p Uptime.dhms.join(', ') # Get individual units p Uptime.days p Uptime.hours p Uptime.minutes p Uptime.seconds # Get the boot time p Uptime.boot_time = Notes - On MS Windows the Uptime.uptime and Uptime_boot_time methods optionally + On MS Windows the Uptime.uptime and Uptime.boot_time methods optionally takes a host name as a single argument. The default is localhost. The current time, users and load average are not included in this library module, even though you may be used to seeing them with the command line version of 'uptime'. == Known Bugs - None that I am aware of. Please log any bugs you find on the project + None that I am aware of. Please log any bugs you find on the project website at https://github.com/djberg96/sys-uptime. == Questions "Doesn't Struct::Tms do this?" - No. == License - Apache 2.0 + Apache-2.0 == Copyright - Copyright 2002-2018, Daniel J. Berger + Copyright 2002-2019, Daniel J. Berger All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Ruby itself. == Warranty This library is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose. == Acknowledgements Andrea Fazzi for help with the FFI version. Mike Hall for help with the BSD side of things for the original C code. Ola Eriksson, whose source code I shamelessly plagiarized to get a better implementation for systems that have the utmpx.h header file for the original C code. == Author Daniel J. Berger
djberg96/sys-uptime
9867409753ab4fab011e3afbcda28050fc159fe1
Fix license name (missing hyphen).
diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index d8ac7c0..41d7de0 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,31 +1,31 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' spec.version = '0.7.2' spec.author = 'Daniel J. Berger' - spec.license = 'Apache 2.0' + spec.license = 'Apache-2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'test/test_sys_uptime.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] spec.extra_rdoc_files = ['CHANGES', 'README', 'MANIFEST'] spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/ffi/CHANGES', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
170cf2429fb97c8373ec8b4c32d9869c35e2e643
Metadata fix for changelog.
diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 8ee94b0..d8ac7c0 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,31 +1,31 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' spec.version = '0.7.2' spec.author = 'Daniel J. Berger' spec.license = 'Apache 2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'test/test_sys_uptime.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] spec.extra_rdoc_files = ['CHANGES', 'README', 'MANIFEST'] spec.metadata = { 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', - 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/master/CHANGES', + 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/ffi/CHANGES', 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki' } spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
b4d574fd03cd532de3aa537865c0ae014338459a
Freeze VERSION constant and add frozen test.
diff --git a/lib/sys/uptime.rb b/lib/sys/uptime.rb index 414a868..1e92e0c 100644 --- a/lib/sys/uptime.rb +++ b/lib/sys/uptime.rb @@ -1,12 +1,12 @@ if File::ALT_SEPARATOR require_relative 'windows/sys/uptime' else require_relative 'unix/sys/uptime' end module Sys class Uptime # The version of the sys-uptime library - VERSION = '0.7.1' + VERSION = '0.7.2'.freeze end end diff --git a/test/test_sys_uptime.rb b/test/test_sys_uptime.rb index 2bf1e72..c058150 100644 --- a/test/test_sys_uptime.rb +++ b/test/test_sys_uptime.rb @@ -1,106 +1,107 @@ ##################################################################### # test_sys_uptime.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'test-unit' require 'socket' include Sys class TC_Sys_Uptime < Test::Unit::TestCase test "version is set to expected value" do - assert_equal('0.7.1', Uptime::VERSION) + assert_equal('0.7.2', Uptime::VERSION) + assert_true(Uptime::VERSION.frozen?) end test "seconds method basic functionality" do assert_respond_to(Uptime, :seconds) assert_nothing_raised{ Uptime.seconds } end test "seconds method returns a plausible value" do assert_kind_of(Integer, Uptime.seconds) assert_true(Uptime.seconds > 300) end test "minutes method basic functionality" do assert_respond_to(Uptime, :minutes) assert_nothing_raised{ Uptime.minutes } end test "minutes method returns a plausible value" do assert_kind_of(Integer, Uptime.minutes) assert_true(Uptime.minutes > 5) end test "hours method basic functionality" do assert_respond_to(Uptime, :hours) assert_nothing_raised{ Uptime.hours } end test "hours method returns a plausible value" do assert_kind_of(Integer, Uptime.hours) assert_true(Uptime.hours > 0) end test "days method basic functionality" do assert_respond_to(Uptime, :days) assert_nothing_raised{ Uptime.days } end test "days method returns a plausible value" do assert_kind_of(Integer, Uptime.days) assert_true(Uptime.days >= 0) end test "uptime method basic functionality" do assert_respond_to(Uptime, :uptime) assert_nothing_raised{ Uptime.uptime } end test "uptime method returns a non-empty string" do assert_kind_of(String, Uptime.uptime) assert_false(Uptime.uptime.empty?) end test "uptime method does not accept any arguments" do omit_if(File::ALT_SEPARATOR) assert_raise(ArgumentError){ Uptime.uptime(1) } end test "uptime accepts a host name on Windows" do omit_unless(File::ALT_SEPARATOR, "MS Windows only") assert_nothing_raised{ Uptime.uptime(Socket.gethostname) } end test "dhms method basic functionality" do assert_respond_to(Uptime, :dhms) assert_nothing_raised{ Uptime.dhms } assert_kind_of(Array, Uptime.dhms) end test "dhms method returns an array of four elements" do assert_false(Uptime.dhms.empty?) assert_equal(4, Uptime.dhms.length) end test "boot_time method basic functionality" do assert_respond_to(Uptime, :boot_time) assert_nothing_raised{ Uptime.boot_time } end test "boot_time method returns a Time object" do assert_kind_of(Time, Uptime.boot_time) end test "Uptime class cannot be instantiated" do assert_kind_of(StandardError, Uptime::Error.new) end test "Ensure that ffi functions are private" do methods = Uptime.methods(false).map{ |e| e.to_s } assert_false(methods.include?('time')) assert_false(methods.include?('times')) end end
djberg96/sys-uptime
100c8f9a773ee499d0fa70e21d1e97d5135626c4
Added changes for 0.7.2.
diff --git a/CHANGES b/CHANGES index 24d23b3..852aa87 100644 --- a/CHANGES +++ b/CHANGES @@ -1,164 +1,169 @@ +== 0.7.2 - 4-Nov-2018 +* Added metadata to the gemspec. +* The VERSION constant is now frozen. +* Updated cert. + == 0.7.1 - 14-May-2016 * Altered internal layout, which also fixed a require bug. Thanks go to jkburges for the spot. * Moved the VERSION constant into a single file shared by all platforms. == 0.7.0 - 3-Oct-2015 * Changed license to Apache 2.0. * Added a cert. This gem is now signed. * Added a sys-uptime.rb file for convenience. * Gem related tasks in the Rakefile now assume Rubygems 2.x. == 0.6.2 - 8-Nov-2014 * Minor updates to gemspec and Rakefile. == 0.6.1 - 22-Oct-2012 * Refactored a private method in the MS Windows source. * Minor fix for one private method test. * Fixed an RbConfig vs Config warning. Thanks Pedro Carrico. == 0.6.0 - 11-Dec-2011 * Switched Unix code to use FFI. * Removed all of the C related tasks from the Rakefile and added the gem:build and gem:install tasks. * Internal directory layout changes, with appropriate changes to the gemspec. == 0.5.3 - 7-May-2009 * Altered the Uptime.seconds implementation on Linux so that it works with both Ruby 1.8.x and 1.9.x. Thanks go to Alexey Chebotar for the spot. == 0.5.2 - 13-Dec-2008 * Fixed a date/time issue in the Windows version caused by Ruby itself. * Fixed the Uptime.seconds, Uptime.minutes and Uptime.hours methods on MS Windows. * Renamed the test file to 'test_sys_uptime.rb'. * Some minor updates to the Rakefile. == 0.5.1 - 26-Jul-2007 * Fixed bug in the MS Windows version caused by incorrect parsing of an MS specific date format (caused by a bug in Ruby 1.8.6). Thanks go to Robert H. for the spot. * Inlined the Rake installation tasks, so the install.rb file has been removed. * Added an 'install_gem' Rake task, and updated the README installation instructions. == 0.5.0 - 30-Mar-2007 * For platforms that use C code, the code now always uses the sysctl() function if supported by your system. This replaces the platform specific checks I was doing for the various BSD flavors. * Fix for OS X - the Uptime.boot_time method now works. * UptimeError is now Uptime::Error. * Improved RDoc in the uptime.c source code. * Added a Rakefile - users should now use the 'test' and 'install' rake tasks. * Updates to the MANIFEST, README and uptime.txt files. == 0.4.5 - 19-Nov-2006 * Internal layout changes, minor doc updates and gemspec improvements. * No code changes. == 0.4.4 - 30-Jun-2006 * Added inline rdoc documentation to the source files. * Added a gemspec. == 0.4.3 - 18-Dec-2005 * Changed the Linux version to pure Ruby. The current method of determining uptime in unix.c does not work in Linux kernel 2.6+. So, from now on it reads out of /proc/uptime. == 0.4.2 - 6-May-2005 * Fixed a potential boot_time bug. * Removed the version.h file. It's no longer needed since the Windows version is pure Ruby. * NetBSD 2.x and FreeBSD 5.x now supported. * Removed the INSTALL file. Installation instructions are now in the README file. * Removed the uptime.rd file. You can generate html documentation by running rdoc over the uptime.txt file. * Made most documents rdoc friendly. * Moved project to RubyForge. == 0.4.1 - 14-Dec-2004 * Moved freebsd code into unix.c file. * Should now work past 249 days (2**31) on systems that have utmpx.h. * Fixed a bug with regards to boot_time, where it was possible that it would simply be empty. == 0.4.0 - 8-Jul-2004 * Removed all reference to the CLK_TCK constant, as per documentation from Richard Stevens that it is deprecated and that sysconf() should be used instead (well, I knew about this, but ignored it until now). * Scrapped the C version for Windows in favor of a pure Ruby version that uses win32ole + WMI. * Added a boot_time method for Unix systems (Windows already had this). * Added an UptimeError class on Unix systems (and replaced UptimeException on Windows). * Modified an internal function to raise an UptimeError if the times() function fails. Also, it now returns an unsigned long instead of a plain long. * Replaced the two different test suites with a single, unified test suite. * Cleaned up the extconf.rb script. I now assume that TestUnit is installed. * Removed the load_avg method (which was never advertised and which I hope you weren't using). You can find a load_avg method in the sys-cpu package. * Changed uptime.rd2 to uptime.rd to be consistent with my other packages. * Removed the uptime.html file - you may generate that on your own. * Added warranty and license info. == 0.3.2 - 30-Dec-2003 * Cleaned up some warnings that showed up with -Wall on some unix platforms (int vs long format, explicit include) * Minor test suite and extconf.rb changes == 0.3.1 - 25-Jun-2003 * Modified test files to handle HP-UX extensions * Minor doc updates * Added the dhms() method. Actually, this was in the 0.3.0 release, I just forgot to mention it in this file :) == 0.3.0 - 22-Jun-2003 * Added OS X support - thanks go to Mike Hall for the patch * Fixed incorrect values in FreeBSD (again Mike Hall) * Modified tc_unix.rb test suite to handle OS X, along with a bit * of minor cleanup * Removed VERSION class method. Use the constant instead * Separated FreeBSD/OS X source into its own file (freebsd.c). The #ifdefs were starting to get too ugly for me == 0.2.1 - 13-May-2003 * Fixed bug in extconf.rb file, and made some major changes * Modified test.rb for those without TestUnit * Modified TestUnit tests - some bogus tests were removed * Added a README file with some additional info * Created a version.h file, so that I can keep the VERSION number in one place * Docs automatically included in doc directory (i.e. no more interactive document creation) == 0.2.0 - 13-Mar-2003 * Added MS Windows support * Added a VERSION constant * Added a test suite (for those with TestUnit installed) * Internal directory layout change * uptime.c is now split into unix.c and windows.c (and linked appropriately) * Changelog and Manifest are now CHANGES and MANIFEST, respectively * Many changes to extconf.rb == 0.1.3 - 6-Jan-2003 * Added a VERSION class method * Added a copyright notice * Fixed up the docs a bit and moved them to the doc directory * Changed the tarball name to match the RAA package name * Modified test.rb script to make it better * Changed install instructions slightly == 0.1.2 - 25-Aug-2002 * Slight change to preprocessor commands to avoid redefining CLK_TCK on those systems that define it in time.h * Added an INSTALL file == 0.1.1 - 21-Jun-2002 * The CLK_TCK constant wasn't necessarily being set correctly, which could lead to some odd results. This has been fixed. == 0.1.0 - 17-Jun-2002 * Initial release
djberg96/sys-uptime
1f81ecd17bb47b196316ba708da6cad9e0e6b67d
Add metadata, update version.
diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 2694259..8ee94b0 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,22 +1,31 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' - spec.version = '0.7.1' + spec.version = '0.7.2' spec.author = 'Daniel J. Berger' spec.license = 'Apache 2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'test/test_sys_uptime.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] spec.extra_rdoc_files = ['CHANGES', 'README', 'MANIFEST'] + spec.metadata = { + 'homepage_uri' => 'https://github.com/djberg96/sys-uptime', + 'bug_tracker_uri' => 'https://github.com/djberg96/sys-uptime/issues', + 'changelog_uri' => 'https://github.com/djberg96/sys-uptime/blob/master/CHANGES', + 'documentation_uri' => 'https://github.com/djberg96/sys-uptime/wiki', + 'source_code_uri' => 'https://github.com/djberg96/sys-uptime', + 'wiki_uri' => 'https://github.com/djberg96/sys-uptime/wiki' + } + spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
39688cfe91591a5fec6c1a9980e5631e175cfa40
Fix test warning.
diff --git a/test/test_sys_uptime.rb b/test/test_sys_uptime.rb index f6352d1..2bf1e72 100644 --- a/test/test_sys_uptime.rb +++ b/test/test_sys_uptime.rb @@ -1,106 +1,106 @@ ##################################################################### # test_sys_uptime.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'test-unit' require 'socket' include Sys class TC_Sys_Uptime < Test::Unit::TestCase test "version is set to expected value" do assert_equal('0.7.1', Uptime::VERSION) end test "seconds method basic functionality" do assert_respond_to(Uptime, :seconds) assert_nothing_raised{ Uptime.seconds } end test "seconds method returns a plausible value" do assert_kind_of(Integer, Uptime.seconds) assert_true(Uptime.seconds > 300) end test "minutes method basic functionality" do assert_respond_to(Uptime, :minutes) assert_nothing_raised{ Uptime.minutes } end test "minutes method returns a plausible value" do assert_kind_of(Integer, Uptime.minutes) assert_true(Uptime.minutes > 5) end test "hours method basic functionality" do assert_respond_to(Uptime, :hours) assert_nothing_raised{ Uptime.hours } end test "hours method returns a plausible value" do assert_kind_of(Integer, Uptime.hours) assert_true(Uptime.hours > 0) end test "days method basic functionality" do assert_respond_to(Uptime, :days) assert_nothing_raised{ Uptime.days } end test "days method returns a plausible value" do - assert_kind_of(Fixnum, Uptime.days) + assert_kind_of(Integer, Uptime.days) assert_true(Uptime.days >= 0) end test "uptime method basic functionality" do assert_respond_to(Uptime, :uptime) assert_nothing_raised{ Uptime.uptime } end test "uptime method returns a non-empty string" do assert_kind_of(String, Uptime.uptime) assert_false(Uptime.uptime.empty?) end test "uptime method does not accept any arguments" do omit_if(File::ALT_SEPARATOR) assert_raise(ArgumentError){ Uptime.uptime(1) } end test "uptime accepts a host name on Windows" do omit_unless(File::ALT_SEPARATOR, "MS Windows only") assert_nothing_raised{ Uptime.uptime(Socket.gethostname) } end test "dhms method basic functionality" do assert_respond_to(Uptime, :dhms) assert_nothing_raised{ Uptime.dhms } assert_kind_of(Array, Uptime.dhms) end test "dhms method returns an array of four elements" do assert_false(Uptime.dhms.empty?) assert_equal(4, Uptime.dhms.length) end test "boot_time method basic functionality" do assert_respond_to(Uptime, :boot_time) assert_nothing_raised{ Uptime.boot_time } end test "boot_time method returns a Time object" do assert_kind_of(Time, Uptime.boot_time) end test "Uptime class cannot be instantiated" do assert_kind_of(StandardError, Uptime::Error.new) end test "Ensure that ffi functions are private" do methods = Uptime.methods(false).map{ |e| e.to_s } assert_false(methods.include?('time')) assert_false(methods.include?('times')) end end
djberg96/sys-uptime
15e90c82348863693b4e30d525633f62b6031af7
Added changes for 0.7.1.
diff --git a/CHANGES b/CHANGES index 5d71044..24d23b3 100644 --- a/CHANGES +++ b/CHANGES @@ -1,159 +1,164 @@ +== 0.7.1 - 14-May-2016 +* Altered internal layout, which also fixed a require bug. Thanks go + to jkburges for the spot. +* Moved the VERSION constant into a single file shared by all platforms. + == 0.7.0 - 3-Oct-2015 * Changed license to Apache 2.0. * Added a cert. This gem is now signed. * Added a sys-uptime.rb file for convenience. * Gem related tasks in the Rakefile now assume Rubygems 2.x. == 0.6.2 - 8-Nov-2014 * Minor updates to gemspec and Rakefile. == 0.6.1 - 22-Oct-2012 * Refactored a private method in the MS Windows source. * Minor fix for one private method test. * Fixed an RbConfig vs Config warning. Thanks Pedro Carrico. == 0.6.0 - 11-Dec-2011 * Switched Unix code to use FFI. * Removed all of the C related tasks from the Rakefile and added the gem:build and gem:install tasks. * Internal directory layout changes, with appropriate changes to the gemspec. == 0.5.3 - 7-May-2009 * Altered the Uptime.seconds implementation on Linux so that it works with both Ruby 1.8.x and 1.9.x. Thanks go to Alexey Chebotar for the spot. == 0.5.2 - 13-Dec-2008 * Fixed a date/time issue in the Windows version caused by Ruby itself. * Fixed the Uptime.seconds, Uptime.minutes and Uptime.hours methods on MS Windows. * Renamed the test file to 'test_sys_uptime.rb'. * Some minor updates to the Rakefile. == 0.5.1 - 26-Jul-2007 * Fixed bug in the MS Windows version caused by incorrect parsing of an MS specific date format (caused by a bug in Ruby 1.8.6). Thanks go to Robert H. for the spot. * Inlined the Rake installation tasks, so the install.rb file has been removed. * Added an 'install_gem' Rake task, and updated the README installation instructions. == 0.5.0 - 30-Mar-2007 * For platforms that use C code, the code now always uses the sysctl() function if supported by your system. This replaces the platform specific checks I was doing for the various BSD flavors. * Fix for OS X - the Uptime.boot_time method now works. * UptimeError is now Uptime::Error. * Improved RDoc in the uptime.c source code. * Added a Rakefile - users should now use the 'test' and 'install' rake tasks. * Updates to the MANIFEST, README and uptime.txt files. == 0.4.5 - 19-Nov-2006 * Internal layout changes, minor doc updates and gemspec improvements. * No code changes. == 0.4.4 - 30-Jun-2006 * Added inline rdoc documentation to the source files. * Added a gemspec. == 0.4.3 - 18-Dec-2005 * Changed the Linux version to pure Ruby. The current method of determining uptime in unix.c does not work in Linux kernel 2.6+. So, from now on it reads out of /proc/uptime. == 0.4.2 - 6-May-2005 * Fixed a potential boot_time bug. * Removed the version.h file. It's no longer needed since the Windows version is pure Ruby. * NetBSD 2.x and FreeBSD 5.x now supported. * Removed the INSTALL file. Installation instructions are now in the README file. * Removed the uptime.rd file. You can generate html documentation by running rdoc over the uptime.txt file. * Made most documents rdoc friendly. * Moved project to RubyForge. == 0.4.1 - 14-Dec-2004 * Moved freebsd code into unix.c file. * Should now work past 249 days (2**31) on systems that have utmpx.h. * Fixed a bug with regards to boot_time, where it was possible that it would simply be empty. == 0.4.0 - 8-Jul-2004 * Removed all reference to the CLK_TCK constant, as per documentation from Richard Stevens that it is deprecated and that sysconf() should be used instead (well, I knew about this, but ignored it until now). * Scrapped the C version for Windows in favor of a pure Ruby version that uses win32ole + WMI. * Added a boot_time method for Unix systems (Windows already had this). * Added an UptimeError class on Unix systems (and replaced UptimeException on Windows). * Modified an internal function to raise an UptimeError if the times() function fails. Also, it now returns an unsigned long instead of a plain long. * Replaced the two different test suites with a single, unified test suite. * Cleaned up the extconf.rb script. I now assume that TestUnit is installed. * Removed the load_avg method (which was never advertised and which I hope you weren't using). You can find a load_avg method in the sys-cpu package. * Changed uptime.rd2 to uptime.rd to be consistent with my other packages. * Removed the uptime.html file - you may generate that on your own. * Added warranty and license info. == 0.3.2 - 30-Dec-2003 * Cleaned up some warnings that showed up with -Wall on some unix platforms (int vs long format, explicit include) * Minor test suite and extconf.rb changes == 0.3.1 - 25-Jun-2003 * Modified test files to handle HP-UX extensions * Minor doc updates * Added the dhms() method. Actually, this was in the 0.3.0 release, I just forgot to mention it in this file :) == 0.3.0 - 22-Jun-2003 * Added OS X support - thanks go to Mike Hall for the patch * Fixed incorrect values in FreeBSD (again Mike Hall) * Modified tc_unix.rb test suite to handle OS X, along with a bit * of minor cleanup * Removed VERSION class method. Use the constant instead * Separated FreeBSD/OS X source into its own file (freebsd.c). The #ifdefs were starting to get too ugly for me == 0.2.1 - 13-May-2003 * Fixed bug in extconf.rb file, and made some major changes * Modified test.rb for those without TestUnit * Modified TestUnit tests - some bogus tests were removed * Added a README file with some additional info * Created a version.h file, so that I can keep the VERSION number in one place * Docs automatically included in doc directory (i.e. no more interactive document creation) == 0.2.0 - 13-Mar-2003 * Added MS Windows support * Added a VERSION constant * Added a test suite (for those with TestUnit installed) * Internal directory layout change * uptime.c is now split into unix.c and windows.c (and linked appropriately) * Changelog and Manifest are now CHANGES and MANIFEST, respectively * Many changes to extconf.rb == 0.1.3 - 6-Jan-2003 * Added a VERSION class method * Added a copyright notice * Fixed up the docs a bit and moved them to the doc directory * Changed the tarball name to match the RAA package name * Modified test.rb script to make it better * Changed install instructions slightly == 0.1.2 - 25-Aug-2002 * Slight change to preprocessor commands to avoid redefining CLK_TCK on those systems that define it in time.h * Added an INSTALL file == 0.1.1 - 21-Jun-2002 * The CLK_TCK constant wasn't necessarily being set correctly, which could lead to some odd results. This has been fixed. == 0.1.0 - 17-Jun-2002 * Initial release
djberg96/sys-uptime
e231895b23a71572c05d0a0494d626a09b57bbe3
Version test bump.
diff --git a/test/test_sys_uptime.rb b/test/test_sys_uptime.rb index 5c263f0..f6352d1 100644 --- a/test/test_sys_uptime.rb +++ b/test/test_sys_uptime.rb @@ -1,106 +1,106 @@ ##################################################################### # test_sys_uptime.rb # # Test suite for sys-uptime. This should generally be run via the # 'rake test' task, since it handles the pre-setup code for you. ##################################################################### require 'sys/uptime' require 'test-unit' require 'socket' include Sys class TC_Sys_Uptime < Test::Unit::TestCase test "version is set to expected value" do - assert_equal('0.7.0', Uptime::VERSION) + assert_equal('0.7.1', Uptime::VERSION) end test "seconds method basic functionality" do assert_respond_to(Uptime, :seconds) assert_nothing_raised{ Uptime.seconds } end test "seconds method returns a plausible value" do assert_kind_of(Integer, Uptime.seconds) assert_true(Uptime.seconds > 300) end test "minutes method basic functionality" do assert_respond_to(Uptime, :minutes) assert_nothing_raised{ Uptime.minutes } end test "minutes method returns a plausible value" do assert_kind_of(Integer, Uptime.minutes) assert_true(Uptime.minutes > 5) end test "hours method basic functionality" do assert_respond_to(Uptime, :hours) assert_nothing_raised{ Uptime.hours } end test "hours method returns a plausible value" do assert_kind_of(Integer, Uptime.hours) assert_true(Uptime.hours > 0) end test "days method basic functionality" do assert_respond_to(Uptime, :days) assert_nothing_raised{ Uptime.days } end test "days method returns a plausible value" do assert_kind_of(Fixnum, Uptime.days) assert_true(Uptime.days >= 0) end test "uptime method basic functionality" do assert_respond_to(Uptime, :uptime) assert_nothing_raised{ Uptime.uptime } end test "uptime method returns a non-empty string" do assert_kind_of(String, Uptime.uptime) assert_false(Uptime.uptime.empty?) end test "uptime method does not accept any arguments" do omit_if(File::ALT_SEPARATOR) assert_raise(ArgumentError){ Uptime.uptime(1) } end test "uptime accepts a host name on Windows" do omit_unless(File::ALT_SEPARATOR, "MS Windows only") assert_nothing_raised{ Uptime.uptime(Socket.gethostname) } end test "dhms method basic functionality" do assert_respond_to(Uptime, :dhms) assert_nothing_raised{ Uptime.dhms } assert_kind_of(Array, Uptime.dhms) end test "dhms method returns an array of four elements" do assert_false(Uptime.dhms.empty?) assert_equal(4, Uptime.dhms.length) end test "boot_time method basic functionality" do assert_respond_to(Uptime, :boot_time) assert_nothing_raised{ Uptime.boot_time } end test "boot_time method returns a Time object" do assert_kind_of(Time, Uptime.boot_time) end test "Uptime class cannot be instantiated" do assert_kind_of(StandardError, Uptime::Error.new) end test "Ensure that ffi functions are private" do methods = Uptime.methods(false).map{ |e| e.to_s } assert_false(methods.include?('time')) assert_false(methods.include?('times')) end end
djberg96/sys-uptime
3917298e76f7b3cb193c586986e493ceb363ce02
Version bump.
diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec index 3165499..2694259 100644 --- a/sys-uptime.gemspec +++ b/sys-uptime.gemspec @@ -1,22 +1,22 @@ require 'rubygems' Gem::Specification.new do |spec| spec.name = 'sys-uptime' - spec.version = '0.7.0' + spec.version = '0.7.1' spec.author = 'Daniel J. Berger' spec.license = 'Apache 2.0' spec.email = 'djberg96@gmail.com' spec.homepage = 'https://github.com/djberg96/sys-uptime' spec.summary = 'A Ruby interface for getting system uptime information.' spec.test_file = 'test/test_sys_uptime.rb' spec.files = Dir["**/*"].reject{ |f| f.include?('git') } spec.cert_chain = ['certs/djberg96_pub.pem'] spec.extra_rdoc_files = ['CHANGES', 'README', 'MANIFEST'] spec.description = <<-EOF The sys-uptime library is a simple interface for gathering uptime information. You can retrieve data in seconds, minutes, days, hours, or all of the above. EOF end
djberg96/sys-uptime
6cf7814c2bbce6090355c030b7e0ac885c55cb67
Remove VERSION constant, use unified VERSION.
diff --git a/lib/sys/unix/sys/uptime.rb b/lib/sys/unix/sys/uptime.rb index 087e4ed..72ef553 100644 --- a/lib/sys/unix/sys/uptime.rb +++ b/lib/sys/unix/sys/uptime.rb @@ -1,213 +1,210 @@ require 'ffi' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime extend FFI::Library ffi_lib FFI::Library::LIBC # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end - # The version of the sys-uptime library - VERSION = '0.7.0' - private # Hit this issue on Linux, not sure why begin find_type(:clock_t) rescue TypeError typedef(:long, :clock_t) end attach_function :strerror, [:int], :string attach_function :sysconf, [:int], :long attach_function :time, [:pointer], :time_t attach_function :times, [:pointer], :clock_t private_class_method :strerror, :sysconf, :time, :times begin attach_function :sysctl, [:pointer, :uint, :pointer, :pointer, :pointer, :size_t], :int private_class_method :sysctl rescue FFI::NotFoundError attach_function :setutxent, [], :void attach_function :getutxent, [], :pointer attach_function :endutxent, [], :void private_class_method :setutxent, :getutxent, :endutxent end CTL_KERN = 1 # Kernel KERN_BOOTTIME = 21 # Time kernel was booted TICKS = 100 # Ticks per second (TODO: use sysconf) BOOT_TIME = 2 # Boot time class Tms < FFI::Struct layout( :tms_utime, :clock_t, :tms_stime, :clock_t, :tms_cutime, :clock_t, :tms_cstime, :clock_t ) end class Timeval < FFI::Struct layout( :tv_sec, :long, :tv_usec, :long ) end class ExitStatus < FFI::Struct layout( :e_termination, :short, :e_exit, :short ) end class Utmpx < FFI::Struct layout( :ut_user, [:char, 32], :ut_id, [:char, 4], :ut_line, [:char, 32], :ut_pid, :pid_t, :ut_type, :short, :ut_exit, ExitStatus, :ut_tv, Timeval, :ut_session, :int, :padding, [:int, 5], :ut_host, [:char, 257] ) end public # Returns a Time object indicating the time the system was last booted. # # Example: # # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 # def self.boot_time if RbConfig::CONFIG['host_os'] =~ /linux/i Time.now - self.seconds elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end Time.at(tv[:tv_sec], tv[:tv_usec]) else begin setutxent() while ent = Utmpx.new(getutxent()) if ent[:ut_type] == BOOT_TIME time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) break end end ensure endutxent() end time end end # Returns the total number of seconds of uptime. # # Example: # # Sys::Uptime.seconds => 118800 # def self.seconds if RbConfig::CONFIG['host_os'] =~ /linux/i begin IO.read('/proc/uptime').split.first.to_i rescue Exception => err raise Error, err end elsif respond_to?(:sysctl, true) tv = Timeval.new mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) if sysctl(mib, 2, tv, size, nil, 0) != 0 raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) end time(nil) - tv[:tv_sec] else tms = Tms.new times(tms) / TICKS end end # Returns the total number of minutes of uptime. # # Example: # # Sys::Uptime.minutes # => 678 # def self.minutes seconds / 60 end # Returns the total number of hours of uptime. # # Example: # # Sys::Uptime.hours # => 31 # def self.hours seconds / 3600 end # Returns the total number of days of uptime. # # Example: # # Sys::Uptime.days # => 2 # def self.days seconds / 86400 end # Returns the uptime as a colon separated string, including days, # hours, minutes and seconds. # # Example: # # Sys::Uptime.uptime # => "1:9:24:57" # def self.uptime secs = seconds days = secs / 86400 secs -= days * 86400 hours = secs / 3600 secs -= hours * 3600 mins = secs / 60 secs -= mins * 60 "#{days}:#{hours}:#{mins}:#{secs}" end # Returns the uptime as a four element array, including days, hours, # minutes and seconds. # # Example: # # Sys::Uptime.dhms # => [1,9,24,57] # def self.dhms uptime.split(':') end end end diff --git a/lib/sys/windows/sys/uptime.rb b/lib/sys/windows/sys/uptime.rb index 76cf52b..7eb627a 100644 --- a/lib/sys/windows/sys/uptime.rb +++ b/lib/sys/windows/sys/uptime.rb @@ -1,147 +1,144 @@ require 'win32ole' require 'socket' require 'date' require 'time' # The Sys module serves as a namespace only. module Sys # The Uptime class encapsulates various bits of information regarding your # system's uptime, including boot time. class Uptime # Error typically raised in one of the Uptime methods should fail. class Error < StandardError; end - # The version of the sys-uptime library. - VERSION = '0.7.0' - # Returns the boot time as a Time object. # # Example: # # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 # def self.boot_time(host = Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => e raise Error, e else query = "select LastBootupTime from Win32_OperatingSystem" results = wmi.ExecQuery(query) results.each{ |ole| time_array = parse_ms_date(ole.LastBootupTime) return Time.mktime(*time_array) } end end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a colon-separated string. # # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.uptime # => "1:9:55:11" # def self.uptime(host = Socket.gethostname) get_dhms(host).join(':') end # Calculates and returns the number of days, hours, minutes and # seconds the +host+ has been running as a four-element Array. # The localhost is used if no +host+ is provided. # # Example: # # Sys::Uptime.dhms # => [1, 9, 55, 11] # def self.dhms(host = Socket.gethostname) get_dhms(host) end # Returns the total number of days the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.days # => 1 # def self.days(host = Socket.gethostname) hours(host) / 24 end # Returns the total number of hours the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.hours # => 33 # def self.hours(host=Socket.gethostname) minutes(host) / 60 end # Returns the total number of minutes the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.minutes # => 1980 # def self.minutes(host=Socket.gethostname) seconds(host) / 60 end # Returns the total number of seconds the system has been up on +host+, # or the localhost if no host is provided. # # Example: # # Sys::Uptime.seconds # => 118800 # def self.seconds(host=Socket.gethostname) get_seconds(host) end private # Converts a string in the format '20040703074625.015625-360' into a # Ruby Time object. # def self.parse_ms_date(str) return if str.nil? return Time.parse(str.split('.').first) end private_class_method :parse_ms_date # Get the actual days, hours, minutes and seconds since boot using WMI. # def self.get_dhms(host) seconds = get_seconds(host) days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 [days, hours, minutes, seconds] end private_class_method :get_dhms # Returns the number of seconds since boot. # def self.get_seconds(host) (Time.now - boot_time).to_i end private_class_method :get_seconds end end
djberg96/sys-uptime
76e8c1316c391cba8dc558f4fa22bfc5b68b3e48
require single file.
diff --git a/lib/sys-uptime.rb b/lib/sys-uptime.rb index 4bd2be7..671bbba 100644 --- a/lib/sys-uptime.rb +++ b/lib/sys-uptime.rb @@ -1,5 +1 @@ -if File::ALT_SEPARATOR - require_relative 'windows/sys/uptime' -else - require_relative 'unix/sys/uptime' -end +require_relative 'sys/uptime'
djberg96/sys-uptime
813756cda161ffedc7d03479e6f3cb3d3c0463e7
Remove require_paths, silence build warnings.
diff --git a/Rakefile b/Rakefile index e544561..818522a 100644 --- a/Rakefile +++ b/Rakefile @@ -1,46 +1,44 @@ require 'rake' require 'rake/clean' require 'rake/testtask' CLEAN.include("**/*.gem", "**/*.rbx", "**/*.rbc") namespace 'gem' do desc 'Build the sys-uptime gem' task :create => [:clean] do require 'rubygems/package' spec = eval(IO.read('sys-uptime.gemspec')) spec.signing_key = File.join(Dir.home, '.ssh', 'gem-private_key.pem') if File::ALT_SEPARATOR - spec.require_paths = ['lib', 'lib/windows'] spec.platform = Gem::Platform::CURRENT spec.platform.cpu = 'universal' spec.platform.version = nil else - spec.require_paths = ['lib', 'lib/unix'] spec.add_dependency('ffi', '>= 1.0.0') end - Gem::Package.build(spec) + Gem::Package.build(spec, true) end desc 'Install the sys-uptime gem' task :install => [:create] do file = Dir["*.gem"].first sh "gem install -l #{file}" end end desc "Run the test suite" Rake::TestTask.new do |t| if File::ALT_SEPARATOR t.libs << 'lib/windows' else t.libs << 'lib/unix' end t.warning = true t.verbose = true end task :default => :test
djberg96/sys-uptime
58e1963b7c1c056437355b22f55a55ce1018e726
Version bump.
diff --git a/CHANGES b/CHANGES new file mode 100644 index 0000000..5d71044 --- /dev/null +++ b/CHANGES @@ -0,0 +1,159 @@ +== 0.7.0 - 3-Oct-2015 +* Changed license to Apache 2.0. +* Added a cert. This gem is now signed. +* Added a sys-uptime.rb file for convenience. +* Gem related tasks in the Rakefile now assume Rubygems 2.x. + +== 0.6.2 - 8-Nov-2014 +* Minor updates to gemspec and Rakefile. + +== 0.6.1 - 22-Oct-2012 +* Refactored a private method in the MS Windows source. +* Minor fix for one private method test. +* Fixed an RbConfig vs Config warning. Thanks Pedro Carrico. + +== 0.6.0 - 11-Dec-2011 +* Switched Unix code to use FFI. +* Removed all of the C related tasks from the Rakefile and added the gem:build + and gem:install tasks. +* Internal directory layout changes, with appropriate changes to the gemspec. + +== 0.5.3 - 7-May-2009 +* Altered the Uptime.seconds implementation on Linux so that it works with + both Ruby 1.8.x and 1.9.x. Thanks go to Alexey Chebotar for the spot. + +== 0.5.2 - 13-Dec-2008 +* Fixed a date/time issue in the Windows version caused by Ruby itself. +* Fixed the Uptime.seconds, Uptime.minutes and Uptime.hours methods on MS + Windows. +* Renamed the test file to 'test_sys_uptime.rb'. +* Some minor updates to the Rakefile. + +== 0.5.1 - 26-Jul-2007 +* Fixed bug in the MS Windows version caused by incorrect parsing of an + MS specific date format (caused by a bug in Ruby 1.8.6). Thanks go to + Robert H. for the spot. +* Inlined the Rake installation tasks, so the install.rb file has been + removed. +* Added an 'install_gem' Rake task, and updated the README installation + instructions. + +== 0.5.0 - 30-Mar-2007 +* For platforms that use C code, the code now always uses the sysctl() + function if supported by your system. This replaces the platform specific + checks I was doing for the various BSD flavors. +* Fix for OS X - the Uptime.boot_time method now works. +* UptimeError is now Uptime::Error. +* Improved RDoc in the uptime.c source code. +* Added a Rakefile - users should now use the 'test' and 'install' rake tasks. +* Updates to the MANIFEST, README and uptime.txt files. + +== 0.4.5 - 19-Nov-2006 +* Internal layout changes, minor doc updates and gemspec improvements. +* No code changes. + +== 0.4.4 - 30-Jun-2006 +* Added inline rdoc documentation to the source files. +* Added a gemspec. + +== 0.4.3 - 18-Dec-2005 +* Changed the Linux version to pure Ruby. The current method of determining + uptime in unix.c does not work in Linux kernel 2.6+. So, from now on it + reads out of /proc/uptime. + +== 0.4.2 - 6-May-2005 +* Fixed a potential boot_time bug. +* Removed the version.h file. It's no longer needed since the Windows + version is pure Ruby. +* NetBSD 2.x and FreeBSD 5.x now supported. +* Removed the INSTALL file. Installation instructions are now in + the README file. +* Removed the uptime.rd file. You can generate html documentation by + running rdoc over the uptime.txt file. +* Made most documents rdoc friendly. +* Moved project to RubyForge. + +== 0.4.1 - 14-Dec-2004 +* Moved freebsd code into unix.c file. +* Should now work past 249 days (2**31) on systems that have utmpx.h. +* Fixed a bug with regards to boot_time, where it was possible that it would + simply be empty. + +== 0.4.0 - 8-Jul-2004 +* Removed all reference to the CLK_TCK constant, as per documentation from + Richard Stevens that it is deprecated and that sysconf() should be used + instead (well, I knew about this, but ignored it until now). +* Scrapped the C version for Windows in favor of a pure Ruby version that + uses win32ole + WMI. +* Added a boot_time method for Unix systems (Windows already had this). +* Added an UptimeError class on Unix systems (and replaced UptimeException + on Windows). +* Modified an internal function to raise an UptimeError if the times() + function fails. Also, it now returns an unsigned long instead of a plain + long. +* Replaced the two different test suites with a single, unified test suite. +* Cleaned up the extconf.rb script. I now assume that TestUnit is installed. +* Removed the load_avg method (which was never advertised and which I hope + you weren't using). You can find a load_avg method in the sys-cpu package. +* Changed uptime.rd2 to uptime.rd to be consistent with my other packages. +* Removed the uptime.html file - you may generate that on your own. +* Added warranty and license info. + +== 0.3.2 - 30-Dec-2003 +* Cleaned up some warnings that showed up with -Wall on some unix platforms + (int vs long format, explicit include) +* Minor test suite and extconf.rb changes + +== 0.3.1 - 25-Jun-2003 +* Modified test files to handle HP-UX extensions +* Minor doc updates +* Added the dhms() method. Actually, this was in the 0.3.0 + release, I just forgot to mention it in this file :) + +== 0.3.0 - 22-Jun-2003 +* Added OS X support - thanks go to Mike Hall for the patch +* Fixed incorrect values in FreeBSD (again Mike Hall) +* Modified tc_unix.rb test suite to handle OS X, along with a bit +* of minor cleanup +* Removed VERSION class method. Use the constant instead +* Separated FreeBSD/OS X source into its own file (freebsd.c). + The #ifdefs were starting to get too ugly for me + +== 0.2.1 - 13-May-2003 +* Fixed bug in extconf.rb file, and made some major changes +* Modified test.rb for those without TestUnit +* Modified TestUnit tests - some bogus tests were removed +* Added a README file with some additional info +* Created a version.h file, so that I can keep the VERSION number + in one place +* Docs automatically included in doc directory (i.e. no more interactive + document creation) + +== 0.2.0 - 13-Mar-2003 +* Added MS Windows support +* Added a VERSION constant +* Added a test suite (for those with TestUnit installed) +* Internal directory layout change +* uptime.c is now split into unix.c and windows.c (and linked appropriately) +* Changelog and Manifest are now CHANGES and MANIFEST, respectively +* Many changes to extconf.rb + +== 0.1.3 - 6-Jan-2003 +* Added a VERSION class method +* Added a copyright notice +* Fixed up the docs a bit and moved them to the doc directory +* Changed the tarball name to match the RAA package name +* Modified test.rb script to make it better +* Changed install instructions slightly + +== 0.1.2 - 25-Aug-2002 +* Slight change to preprocessor commands to avoid redefining CLK_TCK on + those systems that define it in time.h +* Added an INSTALL file + +== 0.1.1 - 21-Jun-2002 +* The CLK_TCK constant wasn't necessarily being set correctly, which could + lead to some odd results. This has been fixed. + +== 0.1.0 - 17-Jun-2002 +* Initial release diff --git a/MANIFEST b/MANIFEST new file mode 100644 index 0000000..5438d88 --- /dev/null +++ b/MANIFEST @@ -0,0 +1,13 @@ +* CHANGES +* MANIFEST +* Rakefile +* README +* install.rb +* sys-uptime.gemspec +* doc/uptime.txt +* examples/test.rb +* ext/extconf.rb +* ext/sys/uptime.c +* lib/sys/linux.rb +* lib/sys/windows.rb +* test/test_sys_uptime.rb \ No newline at end of file diff --git a/README b/README new file mode 100644 index 0000000..95ecba1 --- /dev/null +++ b/README @@ -0,0 +1,66 @@ += Description + A Ruby interface for getting system uptime information. + += Prerequisites + ffi 0.1.0 or later on Unixy platforms. + += Installation + gem install sys-uptime + += Synopsis + require 'sys/uptime' + include Sys + + # Get everything + p Uptime.uptime + p Uptime.dhms.join(', ') + + # Get individual units + p Uptime.days + p Uptime.hours + p Uptime.minutes + p Uptime.seconds + + # Get the boot time + p Uptime.boot_time + += Notes + On MS Windows the Uptime.uptime and Uptime_boot_time methods optionally + takes a host name as a single argument. The default is localhost. + + The current time, users and load average are not included in this library + module, even though you may be used to seeing them with the command + line version of 'uptime'. + +== Known Bugs + None that I am aware of. Please log any bugs you find on the project + website at https://github.com/djberg96/sys-uptime. + +== Questions + "Doesn't Struct::Tms do this?" - No. + +== License + Apache 2.0 + +== Copyright + Copyright 2002-2015, Daniel J. Berger + + All Rights Reserved. This module is free software. It may be used, + redistributed and/or modified under the same terms as Ruby itself. + +== Warranty + This library is provided "as is" and without any express or + implied warranties, including, without limitation, the implied + warranties of merchantability and fitness for a particular purpose. + +== Acknowledgements + Andrea Fazzi for help with the FFI version. + + Mike Hall for help with the BSD side of things for the original C code. + + Ola Eriksson, whose source code I shamelessly plagiarized to get a better + implementation for systems that have the utmpx.h header file for the + original C code. + +== Author + Daniel J. Berger diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..e544561 --- /dev/null +++ b/Rakefile @@ -0,0 +1,46 @@ +require 'rake' +require 'rake/clean' +require 'rake/testtask' + +CLEAN.include("**/*.gem", "**/*.rbx", "**/*.rbc") + +namespace 'gem' do + desc 'Build the sys-uptime gem' + task :create => [:clean] do + require 'rubygems/package' + spec = eval(IO.read('sys-uptime.gemspec')) + spec.signing_key = File.join(Dir.home, '.ssh', 'gem-private_key.pem') + + if File::ALT_SEPARATOR + spec.require_paths = ['lib', 'lib/windows'] + spec.platform = Gem::Platform::CURRENT + spec.platform.cpu = 'universal' + spec.platform.version = nil + else + spec.require_paths = ['lib', 'lib/unix'] + spec.add_dependency('ffi', '>= 1.0.0') + end + + Gem::Package.build(spec) + end + + desc 'Install the sys-uptime gem' + task :install => [:create] do + file = Dir["*.gem"].first + sh "gem install -l #{file}" + end +end + +desc "Run the test suite" +Rake::TestTask.new do |t| + if File::ALT_SEPARATOR + t.libs << 'lib/windows' + else + t.libs << 'lib/unix' + end + + t.warning = true + t.verbose = true +end + +task :default => :test diff --git a/certs/djberg96_pub.pem b/certs/djberg96_pub.pem new file mode 100644 index 0000000..6bea5d3 --- /dev/null +++ b/certs/djberg96_pub.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDcDCCAligAwIBAgIBATANBgkqhkiG9w0BAQUFADA/MREwDwYDVQQDDAhkamJl +cmc5NjEVMBMGCgmSJomT8ixkARkWBWdtYWlsMRMwEQYKCZImiZPyLGQBGRYDY29t +MB4XDTE1MDkwMjIwNDkxOFoXDTE2MDkwMTIwNDkxOFowPzERMA8GA1UEAwwIZGpi +ZXJnOTYxFTATBgoJkiaJk/IsZAEZFgVnbWFpbDETMBEGCgmSJomT8ixkARkWA2Nv +bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMyTkvXqRp6hLs9eoJOS +Hmi8kRYbq9Vkf15/hMxJpotYMgJVHHWrmDcC5Dye2PbnXjTkKf266Zw0PtT9h+lI +S3ts9HO+vaCFSMwFFZmnWJSpQ3CNw2RcHxjWkk9yF7imEM8Kz9ojhiDXzBetdV6M +gr0lV/alUr7TNVBDngbXEfTWscyXh1qd7xZ4EcOdsDktCe5G45N/o3662tPQvJsi +FOF0CM/KuBsa/HL1/eoEmF4B3EKIRfTHrQ3hu20Kv3RJ88QM4ec2+0dd97uX693O +zv6981fyEg+aXLkxrkViM/tz2qR2ZE0jPhHTREPYeMEgptRkTmWSKAuLVWrJEfgl +DtkCAwEAAaN3MHUwCQYDVR0TBAIwADALBgNVHQ8EBAMCBLAwHQYDVR0OBBYEFEwe +nn6bfJADmuIDiMSOzedOrL+xMB0GA1UdEQQWMBSBEmRqYmVyZzk2QGdtYWlsLmNv +bTAdBgNVHRIEFjAUgRJkamJlcmc5NkBnbWFpbC5jb20wDQYJKoZIhvcNAQEFBQAD +ggEBAHmNOCWoDVD75zHFueY0viwGDVP1BNGFC+yXcb7u2GlK+nEMCORqzURbYPf7 +tL+/hzmePIRz7i30UM//64GI1NLv9jl7nIwjhPpXpf7/lu2I9hOTsvwSumb5UiKC +/sqBxI3sfj9pr79Wpv4MuikX1XPik7Ncb7NPsJPw06Lvyc3Hkg5X2XpPtLtS+Gr2 +wKJnmzb5rIPS1cmsqv0M9LPWflzfwoZ/SpnmhagP+g05p8bRNKjZSA2iImM/GyYZ +EJYzxdPOrx2n6NYR3Hk+vHP0U7UBSveI6+qx+ndQYaeyCn+GRX2PKS9h66YF/Q1V +tGSHgAmcLlkdGgan182qsE/4kKM= +-----END CERTIFICATE----- diff --git a/examples/uptime_test.rb b/examples/uptime_test.rb new file mode 100644 index 0000000..03d4ffa --- /dev/null +++ b/examples/uptime_test.rb @@ -0,0 +1,21 @@ +########################################################### +# uptime_test.rb +# +# A generic test script for general futzing. You can run +# this script via the 'rake example' task. +########################################################### +require 'sys/uptime' +include Sys + +print "\nGENERIC TEST SCRIPT FOR SYS-UPTIME\n\n" +puts 'VERSION: ' + Uptime::VERSION + +puts "Days: " + Uptime.days.to_s +puts "Hours: " + Uptime.hours.to_s +puts "Minutes: " + Uptime.minutes.to_s +puts "Seconds: " + Uptime.seconds.to_s +puts "Uptime: " + Uptime.uptime +puts "DHMS: " + Uptime.dhms.join(', ') +puts "Boot Time: " + Uptime.boot_time.to_s + +print "\nTest successful\n" diff --git a/lib/sys-uptime.rb b/lib/sys-uptime.rb new file mode 100644 index 0000000..4bd2be7 --- /dev/null +++ b/lib/sys-uptime.rb @@ -0,0 +1,5 @@ +if File::ALT_SEPARATOR + require_relative 'windows/sys/uptime' +else + require_relative 'unix/sys/uptime' +end diff --git a/lib/unix/sys/uptime.rb b/lib/unix/sys/uptime.rb new file mode 100644 index 0000000..087e4ed --- /dev/null +++ b/lib/unix/sys/uptime.rb @@ -0,0 +1,213 @@ +require 'ffi' + +# The Sys module serves as a namespace only. +module Sys + + # The Uptime class encapsulates various bits of information regarding your + # system's uptime, including boot time. + class Uptime + extend FFI::Library + ffi_lib FFI::Library::LIBC + + # Error typically raised in one of the Uptime methods should fail. + class Error < StandardError; end + + # The version of the sys-uptime library + VERSION = '0.7.0' + + private + + # Hit this issue on Linux, not sure why + begin + find_type(:clock_t) + rescue TypeError + typedef(:long, :clock_t) + end + + attach_function :strerror, [:int], :string + attach_function :sysconf, [:int], :long + attach_function :time, [:pointer], :time_t + attach_function :times, [:pointer], :clock_t + + private_class_method :strerror, :sysconf, :time, :times + + begin + attach_function :sysctl, [:pointer, :uint, :pointer, :pointer, :pointer, :size_t], :int + private_class_method :sysctl + rescue FFI::NotFoundError + attach_function :setutxent, [], :void + attach_function :getutxent, [], :pointer + attach_function :endutxent, [], :void + private_class_method :setutxent, :getutxent, :endutxent + end + + CTL_KERN = 1 # Kernel + KERN_BOOTTIME = 21 # Time kernel was booted + TICKS = 100 # Ticks per second (TODO: use sysconf) + BOOT_TIME = 2 # Boot time + + class Tms < FFI::Struct + layout( + :tms_utime, :clock_t, + :tms_stime, :clock_t, + :tms_cutime, :clock_t, + :tms_cstime, :clock_t + ) + end + + class Timeval < FFI::Struct + layout( + :tv_sec, :long, + :tv_usec, :long + ) + end + + class ExitStatus < FFI::Struct + layout( + :e_termination, :short, + :e_exit, :short + ) + end + + class Utmpx < FFI::Struct + layout( + :ut_user, [:char, 32], + :ut_id, [:char, 4], + :ut_line, [:char, 32], + :ut_pid, :pid_t, + :ut_type, :short, + :ut_exit, ExitStatus, + :ut_tv, Timeval, + :ut_session, :int, + :padding, [:int, 5], + :ut_host, [:char, 257] + ) + end + + public + + # Returns a Time object indicating the time the system was last booted. + # + # Example: + # + # Sys::Uptime.boot_time # => Mon Jul 13 06:08:25 -0600 2009 + # + def self.boot_time + if RbConfig::CONFIG['host_os'] =~ /linux/i + Time.now - self.seconds + elsif respond_to?(:sysctl, true) + tv = Timeval.new + mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) + size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) + + if sysctl(mib, 2, tv, size, nil, 0) != 0 + raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) + end + + Time.at(tv[:tv_sec], tv[:tv_usec]) + else + begin + setutxent() + while ent = Utmpx.new(getutxent()) + if ent[:ut_type] == BOOT_TIME + time = Time.at(ent[:ut_tv][:tv_sec], ent[:ut_tv][:tv_usec]) + break + end + end + ensure + endutxent() + end + time + end + end + + # Returns the total number of seconds of uptime. + # + # Example: + # + # Sys::Uptime.seconds => 118800 + # + def self.seconds + if RbConfig::CONFIG['host_os'] =~ /linux/i + begin + IO.read('/proc/uptime').split.first.to_i + rescue Exception => err + raise Error, err + end + elsif respond_to?(:sysctl, true) + tv = Timeval.new + mib = FFI::MemoryPointer.new(:int, 2).write_array_of_int([CTL_KERN, KERN_BOOTTIME]) + size = FFI::MemoryPointer.new(:long, 1).write_int(tv.size) + + if sysctl(mib, 2, tv, size, nil, 0) != 0 + raise SystemCallError, 'sysctl() - ' + strerror(FFI.errno) + end + + time(nil) - tv[:tv_sec] + else + tms = Tms.new + times(tms) / TICKS + end + end + + # Returns the total number of minutes of uptime. + # + # Example: + # + # Sys::Uptime.minutes # => 678 + # + def self.minutes + seconds / 60 + end + + # Returns the total number of hours of uptime. + # + # Example: + # + # Sys::Uptime.hours # => 31 + # + def self.hours + seconds / 3600 + end + + # Returns the total number of days of uptime. + # + # Example: + # + # Sys::Uptime.days # => 2 + # + def self.days + seconds / 86400 + end + + # Returns the uptime as a colon separated string, including days, + # hours, minutes and seconds. + # + # Example: + # + # Sys::Uptime.uptime # => "1:9:24:57" + # + def self.uptime + secs = seconds + days = secs / 86400 + secs -= days * 86400 + hours = secs / 3600 + secs -= hours * 3600 + mins = secs / 60 + secs -= mins * 60 + + "#{days}:#{hours}:#{mins}:#{secs}" + end + + # Returns the uptime as a four element array, including days, hours, + # minutes and seconds. + # + # Example: + # + # Sys::Uptime.dhms # => [1,9,24,57] + # + def self.dhms + uptime.split(':') + end + end +end diff --git a/lib/windows/sys/uptime.rb b/lib/windows/sys/uptime.rb new file mode 100644 index 0000000..76cf52b --- /dev/null +++ b/lib/windows/sys/uptime.rb @@ -0,0 +1,147 @@ +require 'win32ole' +require 'socket' +require 'date' +require 'time' + +# The Sys module serves as a namespace only. +module Sys + + # The Uptime class encapsulates various bits of information regarding your + # system's uptime, including boot time. + class Uptime + + # Error typically raised in one of the Uptime methods should fail. + class Error < StandardError; end + + # The version of the sys-uptime library. + VERSION = '0.7.0' + + # Returns the boot time as a Time object. + # + # Example: + # + # Sys::Uptime.boot_time # => Fri Dec 12 20:18:58 -0700 2008 + # + def self.boot_time(host = Socket.gethostname) + cs = "winmgmts://#{host}/root/cimv2" + begin + wmi = WIN32OLE.connect(cs) + rescue WIN32OLERuntimeError => e + raise Error, e + else + query = "select LastBootupTime from Win32_OperatingSystem" + results = wmi.ExecQuery(query) + results.each{ |ole| + time_array = parse_ms_date(ole.LastBootupTime) + return Time.mktime(*time_array) + } + end + end + + # Calculates and returns the number of days, hours, minutes and + # seconds the +host+ has been running as a colon-separated string. + # + # The localhost is used if no +host+ is provided. + # + # Example: + # + # Sys::Uptime.uptime # => "1:9:55:11" + # + def self.uptime(host = Socket.gethostname) + get_dhms(host).join(':') + end + + # Calculates and returns the number of days, hours, minutes and + # seconds the +host+ has been running as a four-element Array. + # The localhost is used if no +host+ is provided. + # + # Example: + # + # Sys::Uptime.dhms # => [1, 9, 55, 11] + # + def self.dhms(host = Socket.gethostname) + get_dhms(host) + end + + # Returns the total number of days the system has been up on +host+, + # or the localhost if no host is provided. + # + # Example: + # + # Sys::Uptime.days # => 1 + # + def self.days(host = Socket.gethostname) + hours(host) / 24 + end + + # Returns the total number of hours the system has been up on +host+, + # or the localhost if no host is provided. + # + # Example: + # + # Sys::Uptime.hours # => 33 + # + def self.hours(host=Socket.gethostname) + minutes(host) / 60 + end + + # Returns the total number of minutes the system has been up on +host+, + # or the localhost if no host is provided. + # + # Example: + # + # Sys::Uptime.minutes # => 1980 + # + def self.minutes(host=Socket.gethostname) + seconds(host) / 60 + end + + # Returns the total number of seconds the system has been up on +host+, + # or the localhost if no host is provided. + # + # Example: + # + # Sys::Uptime.seconds # => 118800 + # + def self.seconds(host=Socket.gethostname) + get_seconds(host) + end + + private + + # Converts a string in the format '20040703074625.015625-360' into a + # Ruby Time object. + # + def self.parse_ms_date(str) + return if str.nil? + return Time.parse(str.split('.').first) + end + + private_class_method :parse_ms_date + + # Get the actual days, hours, minutes and seconds since boot using WMI. + # + def self.get_dhms(host) + seconds = get_seconds(host) + + days = (seconds / 86400).to_i + seconds -= days * 86400 + hours = seconds / 3600 + seconds -= hours * 3600 + minutes = seconds / 60 + seconds -= minutes * 60 + + [days, hours, minutes, seconds] + end + + private_class_method :get_dhms + + # Returns the number of seconds since boot. + # + def self.get_seconds(host) + (Time.now - boot_time).to_i + end + + private_class_method :get_seconds + end +end diff --git a/sys-uptime.gemspec b/sys-uptime.gemspec new file mode 100644 index 0000000..3165499 --- /dev/null +++ b/sys-uptime.gemspec @@ -0,0 +1,22 @@ +require 'rubygems' + +Gem::Specification.new do |spec| + spec.name = 'sys-uptime' + spec.version = '0.7.0' + spec.author = 'Daniel J. Berger' + spec.license = 'Apache 2.0' + spec.email = 'djberg96@gmail.com' + spec.homepage = 'https://github.com/djberg96/sys-uptime' + spec.summary = 'A Ruby interface for getting system uptime information.' + spec.test_file = 'test/test_sys_uptime.rb' + spec.files = Dir["**/*"].reject{ |f| f.include?('git') } + spec.cert_chain = ['certs/djberg96_pub.pem'] + + spec.extra_rdoc_files = ['CHANGES', 'README', 'MANIFEST'] + + spec.description = <<-EOF + The sys-uptime library is a simple interface for gathering uptime + information. You can retrieve data in seconds, minutes, days, hours, + or all of the above. + EOF +end diff --git a/test/test_sys_uptime.rb b/test/test_sys_uptime.rb new file mode 100644 index 0000000..5c263f0 --- /dev/null +++ b/test/test_sys_uptime.rb @@ -0,0 +1,106 @@ +##################################################################### +# test_sys_uptime.rb +# +# Test suite for sys-uptime. This should generally be run via the +# 'rake test' task, since it handles the pre-setup code for you. +##################################################################### +require 'sys/uptime' +require 'test-unit' +require 'socket' +include Sys + +class TC_Sys_Uptime < Test::Unit::TestCase + test "version is set to expected value" do + assert_equal('0.7.0', Uptime::VERSION) + end + + test "seconds method basic functionality" do + assert_respond_to(Uptime, :seconds) + assert_nothing_raised{ Uptime.seconds } + end + + test "seconds method returns a plausible value" do + assert_kind_of(Integer, Uptime.seconds) + assert_true(Uptime.seconds > 300) + end + + test "minutes method basic functionality" do + assert_respond_to(Uptime, :minutes) + assert_nothing_raised{ Uptime.minutes } + end + + test "minutes method returns a plausible value" do + assert_kind_of(Integer, Uptime.minutes) + assert_true(Uptime.minutes > 5) + end + + test "hours method basic functionality" do + assert_respond_to(Uptime, :hours) + assert_nothing_raised{ Uptime.hours } + end + + test "hours method returns a plausible value" do + assert_kind_of(Integer, Uptime.hours) + assert_true(Uptime.hours > 0) + end + + test "days method basic functionality" do + assert_respond_to(Uptime, :days) + assert_nothing_raised{ Uptime.days } + end + + test "days method returns a plausible value" do + assert_kind_of(Fixnum, Uptime.days) + assert_true(Uptime.days >= 0) + end + + test "uptime method basic functionality" do + assert_respond_to(Uptime, :uptime) + assert_nothing_raised{ Uptime.uptime } + end + + test "uptime method returns a non-empty string" do + assert_kind_of(String, Uptime.uptime) + assert_false(Uptime.uptime.empty?) + end + + test "uptime method does not accept any arguments" do + omit_if(File::ALT_SEPARATOR) + assert_raise(ArgumentError){ Uptime.uptime(1) } + end + + test "uptime accepts a host name on Windows" do + omit_unless(File::ALT_SEPARATOR, "MS Windows only") + assert_nothing_raised{ Uptime.uptime(Socket.gethostname) } + end + + test "dhms method basic functionality" do + assert_respond_to(Uptime, :dhms) + assert_nothing_raised{ Uptime.dhms } + assert_kind_of(Array, Uptime.dhms) + end + + test "dhms method returns an array of four elements" do + assert_false(Uptime.dhms.empty?) + assert_equal(4, Uptime.dhms.length) + end + + test "boot_time method basic functionality" do + assert_respond_to(Uptime, :boot_time) + assert_nothing_raised{ Uptime.boot_time } + end + + test "boot_time method returns a Time object" do + assert_kind_of(Time, Uptime.boot_time) + end + + test "Uptime class cannot be instantiated" do + assert_kind_of(StandardError, Uptime::Error.new) + end + + test "Ensure that ffi functions are private" do + methods = Uptime.methods(false).map{ |e| e.to_s } + assert_false(methods.include?('time')) + assert_false(methods.include?('times')) + end +end
cfaerber/Graphics-ColorNames-WWW
4d2b5f667eb8571fe56d585ac48638d4acb9fee0
remove dependency on Graphics::ColorNames::HTML, new version 1.14
diff --git a/Changes b/Changes index dc8c1ec..18678c5 100644 --- a/Changes +++ b/Changes @@ -1,30 +1,37 @@ Revision history for Perl extension Graphics::ColorNames::WWW +1.14 Wed May 01 00:00:00 2019 + - remove dependency on deprecated module Graphics::ColorNames::HTML, + which is no longer included in the main Graphics::ColorNames + distribution + FIXES: #127455: Cannot load color naming scheme module + Graphics::ColorNames::HTML + 1.13 Sat Dec 19 00:00:00 2009 - better documentation - fix FAIL in t/11pod_cover.t 1.12 Thu Dec 17 00:00:00 2009 - only use ASCII in POD, fixes FAILs with perl 5.6.x - add examples in eg/ - FIX: #52870 Depending on itself (reported by ANDK) 1.11 Tue Dec 14 00:00:00 2009 - switch to Module::Build - fixes FAILures during make test 1.10 Fri Dec 11 00:00:00 2009 - added Graphics::ColorNames::CSS - re-organisation and cleanup - updated Makefile.PL - added LICENSE, SIGNATURE - use Test::More and Test::NoWarnings - move to Github 1.00 Fri Sep 12 00:00:00 2008 - cleanup 0.01 Sat Nov 26 00:00:00 2005 - first public release diff --git a/MANIFEST b/MANIFEST index 099fee3..9abbd7f 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,20 +1,22 @@ README Changes MANIFEST Build.PL Makefile.PL lib/Graphics/ColorNames/CSS.pm lib/Graphics/ColorNames/IE.pm lib/Graphics/ColorNames/SVG.pm lib/Graphics/ColorNames/WWW.pm t/10pod.t t/11pod_cover.t t/CSS.t t/IExplore.t t/SVG.t t/WWW.t t/WWW_CSS.t -t/WWW_HTML.t t/WWW_IExplore.t t/WWW_Mozilla.t t/WWW_SVG.t +LICENSE +META.yml +META.json diff --git a/README b/README index 9ba5eab..997bc05 100644 --- a/README +++ b/README @@ -1,34 +1,34 @@ Graphics::ColorNames::WWW The "Graphics:ColorNames::WWW" module provides the full list of color names from various Web specifications and implementations. INSTALLATION To install this module type the following: perl Build.PL ./Build ./Build test ./Build install DEPENDENCIES This module requires these other modules and libraries: - Graphics::ColorNames AUTHOR Claus Färber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. LICENSE - Copyright © 2005-2009 Claus Färber. + Copyright © 2005-2019 Claus Färber. Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/lib/Graphics/ColorNames/WWW.pm b/lib/Graphics/ColorNames/WWW.pm index b131b4a..05f0eed 100644 --- a/lib/Graphics/ColorNames/WWW.pm +++ b/lib/Graphics/ColorNames/WWW.pm @@ -1,240 +1,240 @@ package Graphics::ColorNames::WWW; require 5.006; use strict; use warnings; -our $VERSION = '1.13'; +our $VERSION = '1.14'; sub NamesRgbTable() { sub _mk_rgb { ($_[0] << 16) + ($_[1] << 8) + ($_[2]) } use integer; return { 'aliceblue' => _mk_rgb(240, 248, 255), 'antiquewhite' => _mk_rgb(250, 235, 215), 'aqua' => _mk_rgb( 0, 255, 255), 'aquamarine' => _mk_rgb(127, 255, 212), 'azure' => _mk_rgb(240, 255, 255), 'beige' => _mk_rgb(245, 245, 220), 'bisque' => _mk_rgb(255, 228, 196), 'black' => _mk_rgb( 0, 0, 0), 'blanchedalmond' => _mk_rgb(255, 235, 205), 'blue' => _mk_rgb( 0, 0, 255), 'blueviolet' => _mk_rgb(138, 43, 226), 'brown' => _mk_rgb(165, 42, 42), 'burlywood' => _mk_rgb(222, 184, 135), 'cadetblue' => _mk_rgb( 95, 158, 160), 'chartreuse' => _mk_rgb(127, 255, 0), 'chocolate' => _mk_rgb(210, 105, 30), 'coral' => _mk_rgb(255, 127, 80), 'cornflowerblue' => _mk_rgb(100, 149, 237), 'cornsilk' => _mk_rgb(255, 248, 220), 'crimson' => _mk_rgb(220, 20, 60), 'cyan' => _mk_rgb( 0, 255, 255), 'darkblue' => _mk_rgb( 0, 0, 139), 'darkcyan' => _mk_rgb( 0, 139, 139), 'darkgoldenrod' => _mk_rgb(184, 134, 11), 'darkgray' => _mk_rgb(169, 169, 169), 'darkgreen' => _mk_rgb( 0, 100, 0), 'darkgrey' => _mk_rgb(169, 169, 169), 'darkkhaki' => _mk_rgb(189, 183, 107), 'darkmagenta' => _mk_rgb(139, 0, 139), 'darkolivegreen' => _mk_rgb( 85, 107, 47), 'darkorange' => _mk_rgb(255, 140, 0), 'darkorchid' => _mk_rgb(153, 50, 204), 'darkred' => _mk_rgb(139, 0, 0), 'darksalmon' => _mk_rgb(233, 150, 122), 'darkseagreen' => _mk_rgb(143, 188, 143), 'darkslateblue' => _mk_rgb( 72, 61, 139), 'darkslategray' => _mk_rgb( 47, 79, 79), 'darkslategrey' => _mk_rgb( 47, 79, 79), 'darkturquoise' => _mk_rgb( 0, 206, 209), 'darkviolet' => _mk_rgb(148, 0, 211), 'deeppink' => _mk_rgb(255, 20, 147), 'deepskyblue' => _mk_rgb( 0, 191, 255), 'dimgray' => _mk_rgb(105, 105, 105), 'dimgrey' => _mk_rgb(105, 105, 105), 'dodgerblue' => _mk_rgb( 30, 144, 255), 'firebrick' => _mk_rgb(178, 34, 34), 'floralwhite' => _mk_rgb(255, 250, 240), 'forestgreen' => _mk_rgb( 34, 139, 34), 'fuchsia' => 0xff00ff, # "fuscia" is incorrect but common 'fuscia' => 0xff00ff, # mis-spelling... 'gainsboro' => _mk_rgb(220, 220, 220), 'ghostwhite' => _mk_rgb(248, 248, 255), 'gold' => _mk_rgb(255, 215, 0), 'goldenrod' => _mk_rgb(218, 165, 32), 'gray' => _mk_rgb(128, 128, 128), 'grey' => _mk_rgb(128, 128, 128), 'green' => _mk_rgb( 0, 128, 0), 'greenyellow' => _mk_rgb(173, 255, 47), 'honeydew' => _mk_rgb(240, 255, 240), 'hotpink' => _mk_rgb(255, 105, 180), 'indianred' => _mk_rgb(205, 92, 92), 'indigo' => _mk_rgb( 75, 0, 130), 'ivory' => _mk_rgb(255, 255, 240), 'khaki' => _mk_rgb(240, 230, 140), 'lavender' => _mk_rgb(230, 230, 250), 'lavenderblush' => _mk_rgb(255, 240, 245), 'lawngreen' => _mk_rgb(124, 252, 0), 'lemonchiffon' => _mk_rgb(255, 250, 205), 'lightblue' => _mk_rgb(173, 216, 230), 'lightcoral' => _mk_rgb(240, 128, 128), 'lightcyan' => _mk_rgb(224, 255, 255), 'lightgoldenrodyellow' => _mk_rgb(250, 250, 210), 'lightgray' => _mk_rgb(211, 211, 211), 'lightgreen' => _mk_rgb(144, 238, 144), 'lightgrey' => _mk_rgb(211, 211, 211), 'lightpink' => _mk_rgb(255, 182, 193), 'lightsalmon' => _mk_rgb(255, 160, 122), 'lightseagreen' => _mk_rgb( 32, 178, 170), 'lightskyblue' => _mk_rgb(135, 206, 250), 'lightslategray' => _mk_rgb(119, 136, 153), 'lightslategrey' => _mk_rgb(119, 136, 153), 'lightsteelblue' => _mk_rgb(176, 196, 222), 'lightyellow' => _mk_rgb(255, 255, 224), 'lime' => _mk_rgb( 0, 255, 0), 'limegreen' => _mk_rgb( 50, 205, 50), 'linen' => _mk_rgb(250, 240, 230), 'magenta' => _mk_rgb(255, 0, 255), 'maroon' => _mk_rgb(128, 0, 0), 'mediumaquamarine' => _mk_rgb(102, 205, 170), 'mediumblue' => _mk_rgb( 0, 0, 205), 'mediumorchid' => _mk_rgb(186, 85, 211), 'mediumpurple' => _mk_rgb(147, 112, 219), 'mediumseagreen' => _mk_rgb( 60, 179, 113), 'mediumslateblue' => _mk_rgb(123, 104, 238), 'mediumspringgreen' => _mk_rgb( 0, 250, 154), 'mediumturquoise' => _mk_rgb( 72, 209, 204), 'mediumvioletred' => _mk_rgb(199, 21, 133), 'midnightblue' => _mk_rgb( 25, 25, 112), 'mintcream' => _mk_rgb(245, 255, 250), 'mistyrose' => _mk_rgb(255, 228, 225), 'moccasin' => _mk_rgb(255, 228, 181), 'navajowhite' => _mk_rgb(255, 222, 173), 'navy' => _mk_rgb( 0, 0, 128), 'oldlace' => _mk_rgb(253, 245, 230), 'olive' => _mk_rgb(128, 128, 0), 'olivedrab' => _mk_rgb(107, 142, 35), 'orange' => _mk_rgb(255, 165, 0), 'orangered' => _mk_rgb(255, 69, 0), 'orchid' => _mk_rgb(218, 112, 214), 'palegoldenrod' => _mk_rgb(238, 232, 170), 'palegreen' => _mk_rgb(152, 251, 152), 'paleturquoise' => _mk_rgb(175, 238, 238), 'palevioletred' => _mk_rgb(219, 112, 147), 'papayawhip' => _mk_rgb(255, 239, 213), 'peachpuff' => _mk_rgb(255, 218, 185), 'peru' => _mk_rgb(205, 133, 63), 'pink' => _mk_rgb(255, 192, 203), 'plum' => _mk_rgb(221, 160, 221), 'powderblue' => _mk_rgb(176, 224, 230), 'purple' => _mk_rgb(128, 0, 128), 'red' => _mk_rgb(255, 0, 0), 'rosybrown' => _mk_rgb(188, 143, 143), 'royalblue' => _mk_rgb( 65, 105, 225), 'saddlebrown' => _mk_rgb(139, 69, 19), 'salmon' => _mk_rgb(250, 128, 114), 'sandybrown' => _mk_rgb(244, 164, 96), 'seagreen' => _mk_rgb( 46, 139, 87), 'seashell' => _mk_rgb(255, 245, 238), 'sienna' => _mk_rgb(160, 82, 45), 'silver' => _mk_rgb(192, 192, 192), 'skyblue' => _mk_rgb(135, 206, 235), 'slateblue' => _mk_rgb(106, 90, 205), 'slategray' => _mk_rgb(112, 128, 144), 'slategrey' => _mk_rgb(112, 128, 144), 'snow' => _mk_rgb(255, 250, 250), 'springgreen' => _mk_rgb( 0, 255, 127), 'steelblue' => _mk_rgb( 70, 130, 180), 'tan' => _mk_rgb(210, 180, 140), 'teal' => _mk_rgb( 0, 128, 128), 'thistle' => _mk_rgb(216, 191, 216), 'tomato' => _mk_rgb(255, 99, 71), 'turquoise' => _mk_rgb( 64, 224, 208), 'violet' => _mk_rgb(238, 130, 238), 'wheat' => _mk_rgb(245, 222, 179), 'white' => _mk_rgb(255, 255, 255), 'whitesmoke' => _mk_rgb(245, 245, 245), 'yellow' => _mk_rgb(255, 255, 0), 'yellowgreen' => _mk_rgb(154, 205, 50), }; } 1; =head1 NAME Graphics::ColorNames::WWW - WWW color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::WWW; $NameTable = Graphics::ColorNames::WWW->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from various WWW specifications, such as SVG or CSS as well as common browser implementations. See the documentation of L<Graphics::ColorNames> for information how to use this module. Currently, SVG and CSS define the same color keywords and include all color keywords supported by common web browsers. Therefore, the modules Graphics::ColorNames::WWW, L<Graphics::ColorNames::SVG> and L<Graphics::ColorNames::CSS> behave in identical ways. This may change if the specs should happen to diverge; then this module will become a superset of all color keywords defined by W3C's specs. It is recommended to use this module unless you require exact compatibility with the CSS and SVG specifications or specific browsers. =head2 NOTE Reportedly "fuchsia" was misspelled "fuscia" in an unidentified HTML specification. It also appears to be a common misspelling, so both names are recognized. =head1 LIMITATIONS The C<transparent> keyword is unsupported. Currently, Graphics::ColorNames does not allow RGBA values. Further, the system color keywords are not assigned to a fixed RGB value and thus unsupported: C<ActiveBorder>, C<ActiveCaption>, C<AppWorkspace>, C<Background>, C<ButtonFace>, C<ButtonHighlight>, C<ButtonShadow>, C<ButtonText>, C<CaptionText>, C<GrayText>, C<Highlight>, C<HighlightText>, C<InactiveBorder>, C<InactiveCaption>, C<InactiveCaptionText>, C<InfoBackground>, C<InfoText>, C<Menu>, C<MenuText>, C<Scrollbar>, C<ThreeDDarkShadow>, C<ThreeDFace>, C<ThreeDHighlight>, C<ThreeDLightShadow>, C<ThreeDShadow>, C<Window>, C<WindowFrame>, C<WindowText> (these are deprecated in CSS3) =head1 SEE ALSO L<Graphics::ColorNames::HTML>, L<Graphics::ColorNames::CSS>, L<Graphics::ColorNames::SVG> =head1 AUTHOR Claus FE<auml>rber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. =head1 LICENSE Copyright 2005-2009 Claus FE<auml>rber. Copyright 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/t/WWW_HTML.t b/t/WWW_HTML.t deleted file mode 100644 index 4191c53..0000000 --- a/t/WWW_HTML.t +++ /dev/null @@ -1,16 +0,0 @@ -use Test::More tests => 17 + 1; -use Test::NoWarnings; - -use strict; -use Carp; - -use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); -tie my %colors, 'Graphics::ColorNames', 'HTML'; -tie my %col_www, 'Graphics::ColorNames', 'WWW'; - -my $count = 0; -foreach my $name (keys %colors) - { - my @RGB = hex2tuple( $colors{$name} ); - is($name.'-'.tuple2hex(@RGB), $name.'-'.$col_www{$name} ); - }
cfaerber/Graphics-ColorNames-WWW
f9926e2282e8c1488e9e8ae7ec9f6fdac99ca469
new version 1.13: better documentation, fix FAIL in t/11pod_cover.t
diff --git a/Changes b/Changes index 8b00302..dc8c1ec 100644 --- a/Changes +++ b/Changes @@ -1,26 +1,30 @@ Revision history for Perl extension Graphics::ColorNames::WWW +1.13 Sat Dec 19 00:00:00 2009 + - better documentation + - fix FAIL in t/11pod_cover.t + 1.12 Thu Dec 17 00:00:00 2009 - only use ASCII in POD, fixes FAILs with perl 5.6.x - add examples in eg/ - FIX: #52870 Depending on itself (reported by ANDK) 1.11 Tue Dec 14 00:00:00 2009 - switch to Module::Build - fixes FAILures during make test 1.10 Fri Dec 11 00:00:00 2009 - added Graphics::ColorNames::CSS - re-organisation and cleanup - updated Makefile.PL - added LICENSE, SIGNATURE - use Test::More and Test::NoWarnings - move to Github 1.00 Fri Sep 12 00:00:00 2008 - cleanup 0.01 Sat Nov 26 00:00:00 2005 - first public release diff --git a/README b/README index 85e8196..9ba5eab 100644 --- a/README +++ b/README @@ -1,34 +1,34 @@ Graphics::ColorNames::WWW The "Graphics:ColorNames::WWW" module provides the full list of color names from various Web specifications and implementations. INSTALLATION To install this module type the following: - perl Makefile.PL - make - make test - make install + perl Build.PL + ./Build + ./Build test + ./Build install DEPENDENCIES This module requires these other modules and libraries: - Graphics::ColorNames AUTHOR Claus Färber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. LICENSE Copyright © 2005-2009 Claus Färber. Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/lib/Graphics/ColorNames/CSS.pm b/lib/Graphics/ColorNames/CSS.pm index c4076f6..ca0898d 100644 --- a/lib/Graphics/ColorNames/CSS.pm +++ b/lib/Graphics/ColorNames/CSS.pm @@ -1,46 +1,55 @@ package Graphics::ColorNames::CSS; require 5.006; use strict; use warnings; use Graphics::ColorNames::WWW(); -our $VERSION = '1.12'; +our $VERSION = '1.13'; *NamesRgbTable = \&Graphics::ColorNames::WWW::NamesRgbTable; 1; =head1 NAME Graphics::ColorNames::CSS - CSS color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::CSS; $NameTable = Graphics::ColorNames::CSS->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION -This module defines color names and their associated RGB values -from the CSS Color Module Level 3 Working Draft (2008-07-21). +This module defines color names and their associated RGB values from the CSS +Color Module Level 3 W3C Working Draft of 2008-07-21. -It is actually an alias for L<Graphic::ColorNames::WWW>. This may -change in the future should the specs happen to diverge. +It is currently an alias for L<Graphic::ColorNames::WWW>. This may change in +the future. It is recommended to use the WWW module, which will always +implement a superset of this module. + +See the documentation of L<Graphics::ColorNames> for information how to use +this module. + +=head1 SEE ALSO + +L<Graphics::ColorNames::WWW>, +CSS Color Module Level 3 (L<http://w3.org/TR/CSS3-color>) =head1 AUTHOR Claus FE<auml>rber <CFAERBER@cpan.org> =head1 LICENSE Copyright 2005-2009 Claus FE<auml>rber. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Graphics/ColorNames/IE.pm b/lib/Graphics/ColorNames/IE.pm index 85f5008..c185f7f 100644 --- a/lib/Graphics/ColorNames/IE.pm +++ b/lib/Graphics/ColorNames/IE.pm @@ -1,198 +1,203 @@ package Graphics::ColorNames::IE; require 5.006; use strict; use warnings; -our $VERSION = '1.12'; +our $VERSION = '1.13'; sub NamesRgbTable() { use integer; return { (lc 'AliceBlue') => 0xF0F8FF, # 240,248,255 (lc 'AntiqueWhite') => 0xFAEBD7, # 250,235,215 (lc 'Aqua') => 0x00FFFF, # 0,255,255 (lc 'Aquamarine') => 0x7FFFD4, # 127,255,212 (lc 'Azure') => 0xF0FFFF, # 240,255,255 (lc 'Beige') => 0xF5F5DC, # 245,245,220 (lc 'Bisque') => 0xFFE4C4, # 255,228,196 (lc 'Black') => 0x000000, # 0,0,0 (lc 'BlanchedAlmond') => 0xFFEBCD, # 255,235,205 (lc 'Blue') => 0x0000FF, # 0,0,255 (lc 'BlueViolet') => 0x8A2BE2, # 138,43,226 (lc 'Brown') => 0xA52A2A, # 165,42,42 (lc 'BurlyWood') => 0xDEB887, # 222,184,135 (lc 'CadetBlue') => 0x5F9EA0, # 95,158,160 (lc 'Chartreuse') => 0x7FFF00, # 127,255,0 (lc 'Chocolate') => 0xD2691E, # 210,105,30 (lc 'Coral') => 0xFF7F50, # 255,127,80 (lc 'CornflowerBlue') => 0x6495ED, # 100,149,237 (lc 'Cornsilk') => 0xFFF8DC, # 255,248,220 (lc 'Crimson') => 0xDC143C, # 220,20,60 (lc 'Cyan') => 0x00FFFF, # 0,255,255 (lc 'DarkBlue') => 0x00008B, # 0,0,139 (lc 'DarkCyan') => 0x008B8B, # 0,139,139 (lc 'DarkGoldenrod') => 0xB8860B, # 184,134,11 (lc 'DarkGray') => 0xA9A9A9, # 169,169,169 (lc 'DarkGreen') => 0x006400, # 0,100,0 (lc 'DarkKhaki') => 0xBDB76B, # 189,183,107 (lc 'DarkMagenta') => 0x8B008B, # 139,0,139 (lc 'DarkOliveGreen') => 0x556B2F, # 85,107,47 (lc 'DarkOrange') => 0xFF8C00, # 255,140,0 (lc 'DarkOrchid') => 0x9932CC, # 153,50,204 (lc 'DarkRed') => 0x8B0000, # 139,0,0 (lc 'DarkSalmon') => 0xE9967A, # 233,150,122 (lc 'DarkSeaGreen') => 0x8FBC8F, # 143,188,143 (lc 'DarkSlateBlue') => 0x483D8B, # 72,61,139 (lc 'DarkSlateGray') => 0x2F4F4F, # 47,79,79 (lc 'DarkTurquoise') => 0x00CED1, # 0,206,209 (lc 'DarkViolet') => 0x9400D3, # 148,0,211 (lc 'DeepPink') => 0xFF1493, # 255,20,147 (lc 'DeepSkyBlue') => 0x00BFFF, # 0,191,255 (lc 'DimGray') => 0x696969, # 105,105,105 (lc 'DodgerBlue') => 0x1E90FF, # 30,144,255 (lc 'FireBrick') => 0xB22222, # 178,34,34 (lc 'FloralWhite') => 0xFFFAF0, # 255,250,240 (lc 'ForestGreen') => 0x228B22, # 34,139,34 (lc 'Fuchsia') => 0xFF00FF, # 255,0,255 (lc 'Gainsboro') => 0xDCDCDC, # 220,220,220 (lc 'GhostWhite') => 0xF8F8FF, # 248,248,255 (lc 'Gold') => 0xFFD700, # 255,215,0 (lc 'Goldenrod') => 0xDAA520, # 218,165,32 - (lc 'Gray') => 0x808080, # 128,128,128 + (lc 'Gray') => 0x808080, # 128,128,128 ## NB: Grey is missing! (lc 'Green') => 0x008000, # 0,128,0 (lc 'GreenYellow') => 0xADFF2F, # 173,255,47 (lc 'Honeydew') => 0xF0FFF0, # 240,255,240 (lc 'HotPink') => 0xFF69B4, # 255,105,180 (lc 'IndianRed') => 0xCD5C5C, # 205,92,92 (lc 'Indigo') => 0x4B0082, # 75,0,130 (lc 'Ivory') => 0xFFFFF0, # 255,255,240 (lc 'Khaki') => 0xF0E68C, # 240,230,140 (lc 'Lavender') => 0xE6E6FA, # 230,230,250 (lc 'LavenderBlush') => 0xFFF0F5, # 255,240,245 (lc 'LawnGreen') => 0x7CFC00, # 124,252,0 (lc 'LemonChiffon') => 0xFFFACD, # 255,250,205 (lc 'LightBlue') => 0xADD8E6, # 173,216,230 (lc 'LightCoral') => 0xF08080, # 240,128,128 (lc 'LightCyan') => 0xE0FFFF, # 224,255,255 (lc 'LightGoldenrodYellow') => 0xFAFAD2, # 250,250,210 (lc 'LightGreen') => 0x90EE90, # 144,238,144 (lc 'LightGrey') => 0xD3D3D3, # 211,211,211 (lc 'LightPink') => 0xFFB6C1, # 255,182,193 (lc 'LightSalmon') => 0xFFA07A, # 255,160,122 (lc 'LightSeaGreen') => 0x20B2AA, # 32,178,170 (lc 'LightSkyBlue') => 0x87CEFA, # 135,206,250 (lc 'LightSlateGray') => 0x778899, # 119,136,153 (lc 'LightSteelBlue') => 0xB0C4DE, # 176,196,222 (lc 'LightYellow') => 0xFFFFE0, # 255,255,224 (lc 'Lime') => 0x00FF00, # 0,255,0 (lc 'LimeGreen') => 0x32CD32, # 50,205,50 (lc 'Linen') => 0xFAF0E6, # 250,240,230 (lc 'Magenta') => 0xFF00FF, # 255,0,255 (lc 'Maroon') => 0x800000, # 128,0,0 (lc 'MediumAquamarine') => 0x66CDAA, # 102,205,170 (lc 'MediumBlue') => 0x0000CD, # 0,0,205 (lc 'MediumOrchid') => 0xBA55D3, # 186,85,211 (lc 'MediumPurple') => 0x9370DB, # 147,112,219 (lc 'MediumSeaGreen') => 0x3CB371, # 60,179,113 (lc 'MediumSlateBlue') => 0x7B68EE, # 123,104,238 (lc 'MediumSpringGreen') => 0x00FA9A, # 0,250,154 (lc 'MediumTurquoise') => 0x48D1CC, # 72,209,204 (lc 'MediumVioletRed') => 0xC71585, # 199,21,133 (lc 'MidnightBlue') => 0x191970, # 25,25,112 (lc 'MintCream') => 0xF5FFFA, # 245,255,250 (lc 'MistyRose') => 0xFFE4E1, # 255,228,225 (lc 'Moccasin') => 0xFFE4B5, # 255,228,181 (lc 'NavajoWhite') => 0xFFDEAD, # 255,222,173 (lc 'Navy') => 0x000080, # 0,0,128 (lc 'OldLace') => 0xFDF5E6, # 253,245,230 (lc 'Olive') => 0x808000, # 128,128,0 (lc 'OliveDrab') => 0x6B8E23, # 107,142,35 (lc 'Orange') => 0xFFA500, # 255,165,0 (lc 'OrangeRed') => 0xFF4500, # 255,69,0 (lc 'Orchid') => 0xDA70D6, # 218,112,214 (lc 'PaleGoldenrod') => 0xEEE8AA, # 238,232,170 (lc 'PaleGreen') => 0x98FB98, # 152,251,152 (lc 'PaleTurquoise') => 0xAFEEEE, # 175,238,238 (lc 'PaleVioletRed') => 0xDB7093, # 219,112,147 (lc 'PapayaWhip') => 0xFFEFD5, # 255,239,213 (lc 'PeachPuff') => 0xFFDAB9, # 255,218,185 (lc 'Peru') => 0xCD853F, # 205,133,63 (lc 'Pink') => 0xFFC0CB, # 255,192,203 (lc 'Plum') => 0xDDA0DD, # 221,160,221 (lc 'PowderBlue') => 0xB0E0E6, # 176,224,230 (lc 'Purple') => 0x800080, # 128,0,128 (lc 'Red') => 0xFF0000, # 255,0,0 (lc 'RosyBrown') => 0xBC8F8F, # 188,143,143 (lc 'RoyalBlue') => 0x4169E1, # 65,105,225 (lc 'SaddleBrown') => 0x8B4513, # 139,69,19 (lc 'Salmon') => 0xFA8072, # 250,128,114 (lc 'SandyBrown') => 0xF4A460, # 244,164,96 (lc 'SeaGreen') => 0x2E8B57, # 46,139,87 (lc 'Seashell') => 0xFFF5EE, # 255,245,238 (lc 'Sienna') => 0xA0522D, # 160,82,45 (lc 'Silver') => 0xC0C0C0, # 192,192,192 (lc 'SkyBlue') => 0x87CEEB, # 135,206,235 (lc 'SlateBlue') => 0x6A5ACD, # 106,90,205 (lc 'SlateGray') => 0x708090, # 112,128,144 (lc 'Snow') => 0xFFFAFA, # 255,250,250 (lc 'SpringGreen') => 0x00FF7F, # 0,255,127 (lc 'SteelBlue') => 0x4682B4, # 70,130,180 (lc 'Tan') => 0xD2B48C, # 210,180,140 (lc 'Teal') => 0x008080, # 0,128,128 (lc 'Thistle') => 0xD8BFD8, # 216,191,216 (lc 'Tomato') => 0xFF6347, # 255,99,71 (lc 'Turquoise') => 0x40E0D0, # 64,224,208 (lc 'Violet') => 0xEE82EE, # 238,130,238 (lc 'Wheat') => 0xF5DEB3, # 245,222,179 (lc 'White') => 0xFFFFFF, # 255,255,255 (lc 'WhiteSmoke') => 0xF5F5F5, # 245,245,245 (lc 'Yellow') => 0xFFFF00, # 255,255,0 (lc 'YellowGreen') => 0x9ACD32, # 154,205,50 }; } 1; =head1 NAME Graphics::ColorNames::IE - MS Internet Explorer color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::IE; $NameTable = Graphics::ColorNames::IE->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values recognized by Microsoft Internet Explorer. +This currently is a subset of the colors defined by CSS and SVG specifications. + +See the documentation of L<Graphics::ColorNames> for information how to use +this module. + =head2 NOTE Although Microsoft calls them "X11 color names", some of them are not identical to the definitions in the X Specification. =head1 SEE ALSO -C<Graphics::ColorNames>, MSDN <http://msdn.microsoft.com/library/en-us/dnwebgen/html/X11_names.asp> +C<Graphics::ColorNames::WWW>, MSDN <http://msdn.microsoft.com/library/en-us/dnwebgen/html/X11_names.asp> =head1 AUTHOR Claus FE<auml>rber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. =head1 LICENSE Copyright 2005-2009 Claus FE<auml>rber. Copyright 2001-2004 Robert Rothenberg. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Graphics/ColorNames/SVG.pm b/lib/Graphics/ColorNames/SVG.pm index 4ae6589..394a7a6 100644 --- a/lib/Graphics/ColorNames/SVG.pm +++ b/lib/Graphics/ColorNames/SVG.pm @@ -1,47 +1,56 @@ package Graphics::ColorNames::SVG; require 5.006; use strict; use warnings; use Graphics::ColorNames::WWW(); -our $VERSION = '1.12'; +our $VERSION = '1.13'; *NamesRgbTable = \&Graphics::ColorNames::WWW::NamesRgbTable; 1; =head1 NAME Graphics::ColorNames::SVG - SVG color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::SVG; $NameTable = Graphics::ColorNames::SVG->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from the SVG 1.2 Specification. -It is actually an alias for L<Graphic::ColorNames::WWW>. This may -change should the specs happen to diverge. +It is currently an alias for L<Graphic::ColorNames::WWW>. This may change in +the future. It is recommended to use the WWW module, which will always +implement a superset of this module. + +See the documentation of L<Graphics::ColorNames> for information how to use +this module. + +=head1 SEE ALSO + +L<Graphics::ColorNames::WWW>, +Scalable Vector Graphics (SVG) 1.1 Specification, Section 4.2 (L<http://www.w3.org/TR/SVG/types.html#ColorKeywords>) =head1 AUTHOR Claus FE<auml>rber <CFAERBER@cpan.org> =head1 LICENSE Copyright 2008-2009 Claus FE<auml>rber. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Graphics/ColorNames/WWW.pm b/lib/Graphics/ColorNames/WWW.pm index 3358573..b131b4a 100644 --- a/lib/Graphics/ColorNames/WWW.pm +++ b/lib/Graphics/ColorNames/WWW.pm @@ -1,212 +1,240 @@ package Graphics::ColorNames::WWW; require 5.006; use strict; use warnings; -our $VERSION = '1.12'; +our $VERSION = '1.13'; sub NamesRgbTable() { - sub rgb { ($_[0] << 16) + ($_[1] << 8) + ($_[2]) } + sub _mk_rgb { ($_[0] << 16) + ($_[1] << 8) + ($_[2]) } use integer; return { - 'aliceblue' => rgb(240, 248, 255), - 'antiquewhite' => rgb(250, 235, 215), - 'aqua' => rgb( 0, 255, 255), - 'aquamarine' => rgb(127, 255, 212), - 'azure' => rgb(240, 255, 255), - 'beige' => rgb(245, 245, 220), - 'bisque' => rgb(255, 228, 196), - 'black' => rgb( 0, 0, 0), - 'blanchedalmond' => rgb(255, 235, 205), - 'blue' => rgb( 0, 0, 255), - 'blueviolet' => rgb(138, 43, 226), - 'brown' => rgb(165, 42, 42), - 'burlywood' => rgb(222, 184, 135), - 'cadetblue' => rgb( 95, 158, 160), - 'chartreuse' => rgb(127, 255, 0), - 'chocolate' => rgb(210, 105, 30), - 'coral' => rgb(255, 127, 80), - 'cornflowerblue' => rgb(100, 149, 237), - 'cornsilk' => rgb(255, 248, 220), - 'crimson' => rgb(220, 20, 60), - 'cyan' => rgb( 0, 255, 255), - 'darkblue' => rgb( 0, 0, 139), - 'darkcyan' => rgb( 0, 139, 139), - 'darkgoldenrod' => rgb(184, 134, 11), - 'darkgray' => rgb(169, 169, 169), - 'darkgreen' => rgb( 0, 100, 0), - 'darkgrey' => rgb(169, 169, 169), - 'darkkhaki' => rgb(189, 183, 107), - 'darkmagenta' => rgb(139, 0, 139), - 'darkolivegreen' => rgb( 85, 107, 47), - 'darkorange' => rgb(255, 140, 0), - 'darkorchid' => rgb(153, 50, 204), - 'darkred' => rgb(139, 0, 0), - 'darksalmon' => rgb(233, 150, 122), - 'darkseagreen' => rgb(143, 188, 143), - 'darkslateblue' => rgb( 72, 61, 139), - 'darkslategray' => rgb( 47, 79, 79), - 'darkslategrey' => rgb( 47, 79, 79), - 'darkturquoise' => rgb( 0, 206, 209), - 'darkviolet' => rgb(148, 0, 211), - 'deeppink' => rgb(255, 20, 147), - 'deepskyblue' => rgb( 0, 191, 255), - 'dimgray' => rgb(105, 105, 105), - 'dimgrey' => rgb(105, 105, 105), - 'dodgerblue' => rgb( 30, 144, 255), - 'firebrick' => rgb(178, 34, 34), - 'floralwhite' => rgb(255, 250, 240), - 'forestgreen' => rgb( 34, 139, 34), + 'aliceblue' => _mk_rgb(240, 248, 255), + 'antiquewhite' => _mk_rgb(250, 235, 215), + 'aqua' => _mk_rgb( 0, 255, 255), + 'aquamarine' => _mk_rgb(127, 255, 212), + 'azure' => _mk_rgb(240, 255, 255), + 'beige' => _mk_rgb(245, 245, 220), + 'bisque' => _mk_rgb(255, 228, 196), + 'black' => _mk_rgb( 0, 0, 0), + 'blanchedalmond' => _mk_rgb(255, 235, 205), + 'blue' => _mk_rgb( 0, 0, 255), + 'blueviolet' => _mk_rgb(138, 43, 226), + 'brown' => _mk_rgb(165, 42, 42), + 'burlywood' => _mk_rgb(222, 184, 135), + 'cadetblue' => _mk_rgb( 95, 158, 160), + 'chartreuse' => _mk_rgb(127, 255, 0), + 'chocolate' => _mk_rgb(210, 105, 30), + 'coral' => _mk_rgb(255, 127, 80), + 'cornflowerblue' => _mk_rgb(100, 149, 237), + 'cornsilk' => _mk_rgb(255, 248, 220), + 'crimson' => _mk_rgb(220, 20, 60), + 'cyan' => _mk_rgb( 0, 255, 255), + 'darkblue' => _mk_rgb( 0, 0, 139), + 'darkcyan' => _mk_rgb( 0, 139, 139), + 'darkgoldenrod' => _mk_rgb(184, 134, 11), + 'darkgray' => _mk_rgb(169, 169, 169), + 'darkgreen' => _mk_rgb( 0, 100, 0), + 'darkgrey' => _mk_rgb(169, 169, 169), + 'darkkhaki' => _mk_rgb(189, 183, 107), + 'darkmagenta' => _mk_rgb(139, 0, 139), + 'darkolivegreen' => _mk_rgb( 85, 107, 47), + 'darkorange' => _mk_rgb(255, 140, 0), + 'darkorchid' => _mk_rgb(153, 50, 204), + 'darkred' => _mk_rgb(139, 0, 0), + 'darksalmon' => _mk_rgb(233, 150, 122), + 'darkseagreen' => _mk_rgb(143, 188, 143), + 'darkslateblue' => _mk_rgb( 72, 61, 139), + 'darkslategray' => _mk_rgb( 47, 79, 79), + 'darkslategrey' => _mk_rgb( 47, 79, 79), + 'darkturquoise' => _mk_rgb( 0, 206, 209), + 'darkviolet' => _mk_rgb(148, 0, 211), + 'deeppink' => _mk_rgb(255, 20, 147), + 'deepskyblue' => _mk_rgb( 0, 191, 255), + 'dimgray' => _mk_rgb(105, 105, 105), + 'dimgrey' => _mk_rgb(105, 105, 105), + 'dodgerblue' => _mk_rgb( 30, 144, 255), + 'firebrick' => _mk_rgb(178, 34, 34), + 'floralwhite' => _mk_rgb(255, 250, 240), + 'forestgreen' => _mk_rgb( 34, 139, 34), 'fuchsia' => 0xff00ff, # "fuscia" is incorrect but common 'fuscia' => 0xff00ff, # mis-spelling... - 'gainsboro' => rgb(220, 220, 220), - 'ghostwhite' => rgb(248, 248, 255), - 'gold' => rgb(255, 215, 0), - 'goldenrod' => rgb(218, 165, 32), - 'gray' => rgb(128, 128, 128), - 'grey' => rgb(128, 128, 128), - 'green' => rgb( 0, 128, 0), - 'greenyellow' => rgb(173, 255, 47), - 'honeydew' => rgb(240, 255, 240), - 'hotpink' => rgb(255, 105, 180), - 'indianred' => rgb(205, 92, 92), - 'indigo' => rgb( 75, 0, 130), - 'ivory' => rgb(255, 255, 240), - 'khaki' => rgb(240, 230, 140), - 'lavender' => rgb(230, 230, 250), - 'lavenderblush' => rgb(255, 240, 245), - 'lawngreen' => rgb(124, 252, 0), - 'lemonchiffon' => rgb(255, 250, 205), - 'lightblue' => rgb(173, 216, 230), - 'lightcoral' => rgb(240, 128, 128), - 'lightcyan' => rgb(224, 255, 255), - 'lightgoldenrodyellow' => rgb(250, 250, 210), - 'lightgray' => rgb(211, 211, 211), - 'lightgreen' => rgb(144, 238, 144), - 'lightgrey' => rgb(211, 211, 211), - 'lightpink' => rgb(255, 182, 193), - 'lightsalmon' => rgb(255, 160, 122), - 'lightseagreen' => rgb( 32, 178, 170), - 'lightskyblue' => rgb(135, 206, 250), - 'lightslategray' => rgb(119, 136, 153), - 'lightslategrey' => rgb(119, 136, 153), - 'lightsteelblue' => rgb(176, 196, 222), - 'lightyellow' => rgb(255, 255, 224), - 'lime' => rgb( 0, 255, 0), - 'limegreen' => rgb( 50, 205, 50), - 'linen' => rgb(250, 240, 230), - 'magenta' => rgb(255, 0, 255), - 'maroon' => rgb(128, 0, 0), - 'mediumaquamarine' => rgb(102, 205, 170), - 'mediumblue' => rgb( 0, 0, 205), - 'mediumorchid' => rgb(186, 85, 211), - 'mediumpurple' => rgb(147, 112, 219), - 'mediumseagreen' => rgb( 60, 179, 113), - 'mediumslateblue' => rgb(123, 104, 238), - 'mediumspringgreen' => rgb( 0, 250, 154), - 'mediumturquoise' => rgb( 72, 209, 204), - 'mediumvioletred' => rgb(199, 21, 133), - 'midnightblue' => rgb( 25, 25, 112), - 'mintcream' => rgb(245, 255, 250), - 'mistyrose' => rgb(255, 228, 225), - 'moccasin' => rgb(255, 228, 181), - 'navajowhite' => rgb(255, 222, 173), - 'navy' => rgb( 0, 0, 128), - 'oldlace' => rgb(253, 245, 230), - 'olive' => rgb(128, 128, 0), - 'olivedrab' => rgb(107, 142, 35), - 'orange' => rgb(255, 165, 0), - 'orangered' => rgb(255, 69, 0), - 'orchid' => rgb(218, 112, 214), - 'palegoldenrod' => rgb(238, 232, 170), - 'palegreen' => rgb(152, 251, 152), - 'paleturquoise' => rgb(175, 238, 238), - 'palevioletred' => rgb(219, 112, 147), - 'papayawhip' => rgb(255, 239, 213), - 'peachpuff' => rgb(255, 218, 185), - 'peru' => rgb(205, 133, 63), - 'pink' => rgb(255, 192, 203), - 'plum' => rgb(221, 160, 221), - 'powderblue' => rgb(176, 224, 230), - 'purple' => rgb(128, 0, 128), - 'red' => rgb(255, 0, 0), - 'rosybrown' => rgb(188, 143, 143), - 'royalblue' => rgb( 65, 105, 225), - 'saddlebrown' => rgb(139, 69, 19), - 'salmon' => rgb(250, 128, 114), - 'sandybrown' => rgb(244, 164, 96), - 'seagreen' => rgb( 46, 139, 87), - 'seashell' => rgb(255, 245, 238), - 'sienna' => rgb(160, 82, 45), - 'silver' => rgb(192, 192, 192), - 'skyblue' => rgb(135, 206, 235), - 'slateblue' => rgb(106, 90, 205), - 'slategray' => rgb(112, 128, 144), - 'slategrey' => rgb(112, 128, 144), - 'snow' => rgb(255, 250, 250), - 'springgreen' => rgb( 0, 255, 127), - 'steelblue' => rgb( 70, 130, 180), - 'tan' => rgb(210, 180, 140), - 'teal' => rgb( 0, 128, 128), - 'thistle' => rgb(216, 191, 216), - 'tomato' => rgb(255, 99, 71), - 'turquoise' => rgb( 64, 224, 208), - 'violet' => rgb(238, 130, 238), - 'wheat' => rgb(245, 222, 179), - 'white' => rgb(255, 255, 255), - 'whitesmoke' => rgb(245, 245, 245), - 'yellow' => rgb(255, 255, 0), - 'yellowgreen' => rgb(154, 205, 50), + 'gainsboro' => _mk_rgb(220, 220, 220), + 'ghostwhite' => _mk_rgb(248, 248, 255), + 'gold' => _mk_rgb(255, 215, 0), + 'goldenrod' => _mk_rgb(218, 165, 32), + 'gray' => _mk_rgb(128, 128, 128), + 'grey' => _mk_rgb(128, 128, 128), + 'green' => _mk_rgb( 0, 128, 0), + 'greenyellow' => _mk_rgb(173, 255, 47), + 'honeydew' => _mk_rgb(240, 255, 240), + 'hotpink' => _mk_rgb(255, 105, 180), + 'indianred' => _mk_rgb(205, 92, 92), + 'indigo' => _mk_rgb( 75, 0, 130), + 'ivory' => _mk_rgb(255, 255, 240), + 'khaki' => _mk_rgb(240, 230, 140), + 'lavender' => _mk_rgb(230, 230, 250), + 'lavenderblush' => _mk_rgb(255, 240, 245), + 'lawngreen' => _mk_rgb(124, 252, 0), + 'lemonchiffon' => _mk_rgb(255, 250, 205), + 'lightblue' => _mk_rgb(173, 216, 230), + 'lightcoral' => _mk_rgb(240, 128, 128), + 'lightcyan' => _mk_rgb(224, 255, 255), + 'lightgoldenrodyellow' => _mk_rgb(250, 250, 210), + 'lightgray' => _mk_rgb(211, 211, 211), + 'lightgreen' => _mk_rgb(144, 238, 144), + 'lightgrey' => _mk_rgb(211, 211, 211), + 'lightpink' => _mk_rgb(255, 182, 193), + 'lightsalmon' => _mk_rgb(255, 160, 122), + 'lightseagreen' => _mk_rgb( 32, 178, 170), + 'lightskyblue' => _mk_rgb(135, 206, 250), + 'lightslategray' => _mk_rgb(119, 136, 153), + 'lightslategrey' => _mk_rgb(119, 136, 153), + 'lightsteelblue' => _mk_rgb(176, 196, 222), + 'lightyellow' => _mk_rgb(255, 255, 224), + 'lime' => _mk_rgb( 0, 255, 0), + 'limegreen' => _mk_rgb( 50, 205, 50), + 'linen' => _mk_rgb(250, 240, 230), + 'magenta' => _mk_rgb(255, 0, 255), + 'maroon' => _mk_rgb(128, 0, 0), + 'mediumaquamarine' => _mk_rgb(102, 205, 170), + 'mediumblue' => _mk_rgb( 0, 0, 205), + 'mediumorchid' => _mk_rgb(186, 85, 211), + 'mediumpurple' => _mk_rgb(147, 112, 219), + 'mediumseagreen' => _mk_rgb( 60, 179, 113), + 'mediumslateblue' => _mk_rgb(123, 104, 238), + 'mediumspringgreen' => _mk_rgb( 0, 250, 154), + 'mediumturquoise' => _mk_rgb( 72, 209, 204), + 'mediumvioletred' => _mk_rgb(199, 21, 133), + 'midnightblue' => _mk_rgb( 25, 25, 112), + 'mintcream' => _mk_rgb(245, 255, 250), + 'mistyrose' => _mk_rgb(255, 228, 225), + 'moccasin' => _mk_rgb(255, 228, 181), + 'navajowhite' => _mk_rgb(255, 222, 173), + 'navy' => _mk_rgb( 0, 0, 128), + 'oldlace' => _mk_rgb(253, 245, 230), + 'olive' => _mk_rgb(128, 128, 0), + 'olivedrab' => _mk_rgb(107, 142, 35), + 'orange' => _mk_rgb(255, 165, 0), + 'orangered' => _mk_rgb(255, 69, 0), + 'orchid' => _mk_rgb(218, 112, 214), + 'palegoldenrod' => _mk_rgb(238, 232, 170), + 'palegreen' => _mk_rgb(152, 251, 152), + 'paleturquoise' => _mk_rgb(175, 238, 238), + 'palevioletred' => _mk_rgb(219, 112, 147), + 'papayawhip' => _mk_rgb(255, 239, 213), + 'peachpuff' => _mk_rgb(255, 218, 185), + 'peru' => _mk_rgb(205, 133, 63), + 'pink' => _mk_rgb(255, 192, 203), + 'plum' => _mk_rgb(221, 160, 221), + 'powderblue' => _mk_rgb(176, 224, 230), + 'purple' => _mk_rgb(128, 0, 128), + 'red' => _mk_rgb(255, 0, 0), + 'rosybrown' => _mk_rgb(188, 143, 143), + 'royalblue' => _mk_rgb( 65, 105, 225), + 'saddlebrown' => _mk_rgb(139, 69, 19), + 'salmon' => _mk_rgb(250, 128, 114), + 'sandybrown' => _mk_rgb(244, 164, 96), + 'seagreen' => _mk_rgb( 46, 139, 87), + 'seashell' => _mk_rgb(255, 245, 238), + 'sienna' => _mk_rgb(160, 82, 45), + 'silver' => _mk_rgb(192, 192, 192), + 'skyblue' => _mk_rgb(135, 206, 235), + 'slateblue' => _mk_rgb(106, 90, 205), + 'slategray' => _mk_rgb(112, 128, 144), + 'slategrey' => _mk_rgb(112, 128, 144), + 'snow' => _mk_rgb(255, 250, 250), + 'springgreen' => _mk_rgb( 0, 255, 127), + 'steelblue' => _mk_rgb( 70, 130, 180), + 'tan' => _mk_rgb(210, 180, 140), + 'teal' => _mk_rgb( 0, 128, 128), + 'thistle' => _mk_rgb(216, 191, 216), + 'tomato' => _mk_rgb(255, 99, 71), + 'turquoise' => _mk_rgb( 64, 224, 208), + 'violet' => _mk_rgb(238, 130, 238), + 'wheat' => _mk_rgb(245, 222, 179), + 'white' => _mk_rgb(255, 255, 255), + 'whitesmoke' => _mk_rgb(245, 245, 245), + 'yellow' => _mk_rgb(255, 255, 0), + 'yellowgreen' => _mk_rgb(154, 205, 50), }; } 1; =head1 NAME Graphics::ColorNames::WWW - WWW color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::WWW; $NameTable = Graphics::ColorNames::WWW->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION -This module defines color names and their associated RGB values from -various WWW specifications, such as SVG or CSS. +This module defines color names and their associated RGB values from various +WWW specifications, such as SVG or CSS as well as common browser +implementations. +See the documentation of L<Graphics::ColorNames> for information how to use +this module. + +Currently, SVG and CSS define the same color keywords and include all color +keywords supported by common web browsers. Therefore, the modules +Graphics::ColorNames::WWW, L<Graphics::ColorNames::SVG> and +L<Graphics::ColorNames::CSS> behave in identical ways. + +This may change if the specs should happen to diverge; then this module will +become a superset of all color keywords defined by W3C's specs. + +It is recommended to use this module unless you require exact compatibility +with the CSS and SVG specifications or specific browsers. =head2 NOTE Reportedly "fuchsia" was misspelled "fuscia" in an unidentified HTML specification. It also appears to be a common misspelling, so both names are recognized. +=head1 LIMITATIONS + +The C<transparent> keyword is unsupported. Currently, Graphics::ColorNames does +not allow RGBA values. + +Further, the system color keywords are not assigned to a fixed RGB value and +thus unsupported: C<ActiveBorder>, C<ActiveCaption>, C<AppWorkspace>, +C<Background>, C<ButtonFace>, C<ButtonHighlight>, C<ButtonShadow>, +C<ButtonText>, C<CaptionText>, C<GrayText>, C<Highlight>, C<HighlightText>, +C<InactiveBorder>, C<InactiveCaption>, C<InactiveCaptionText>, +C<InfoBackground>, C<InfoText>, C<Menu>, C<MenuText>, C<Scrollbar>, +C<ThreeDDarkShadow>, C<ThreeDFace>, C<ThreeDHighlight>, C<ThreeDLightShadow>, +C<ThreeDShadow>, C<Window>, C<WindowFrame>, C<WindowText> (these are deprecated +in CSS3) + =head1 SEE ALSO -C<Graphics::ColorNames>, -SVG 1.2 Specificiation <http://www.w3.org/SVG/>, -CSS Color Module Level 3 <http://www.w3.org/TR/css3-color>. +L<Graphics::ColorNames::HTML>, L<Graphics::ColorNames::CSS>, +L<Graphics::ColorNames::SVG> =head1 AUTHOR Claus FE<auml>rber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. =head1 LICENSE Copyright 2005-2009 Claus FE<auml>rber. Copyright 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/t/11pod_cover.t b/t/11pod_cover.t index 8e593aa..07f851b 100644 --- a/t/11pod_cover.t +++ b/t/11pod_cover.t @@ -1,13 +1,14 @@ use strict; use Test::More; eval "use Test::Pod::Coverage;"; plan skip_all => "Test::Pod::Coverage required for testing POD coverage" if $@; -plan tests => 2; +plan tests => 4; -pod_coverage_ok( 'Color::Calc', { - trustme => [ qr/_(tuple|html|pdf|hex|obj|object)$/, qr/^color(_.+)?$/ ], - }, 'Color::Calc is covered by POD' ); +my $trm = { 'trustme' => [ 'NamesRgbTable' ] }; # for use by base module -pod_coverage_ok( 'Color::Calc::WWW', 'Color::Calc::WWW is covered by POD' ); +pod_coverage_ok( 'Graphics::ColorNames::WWW', $trm ); +pod_coverage_ok( 'Graphics::ColorNames::SVG', $trm ); +pod_coverage_ok( 'Graphics::ColorNames::IE', $trm ); +pod_coverage_ok( 'Graphics::ColorNames::CSS', $trm );
cfaerber/Graphics-ColorNames-WWW
c77ea9802084d4a100ff1f4ab98183dd09adef6a
new version 1.12
diff --git a/Build.PL b/Build.PL index 4d09616..8a1852f 100644 --- a/Build.PL +++ b/Build.PL @@ -1,31 +1,29 @@ #!/usr/bin/perl use 5.006; use strict; use Module::Build; my $b = Module::Build->new( 'module_name' => 'Graphics::ColorNames::WWW', 'license' => 'perl', 'sign' => 1, 'create_license' => 1, 'create_makefile_pl' => 'traditional', 'requires' => { 'Graphics::ColorNames' => 0.32, - 'Graphics::ColorNames::WWW' => 0.01, - 'Params::Validate' => 0.75, }, 'build_requires' => { 'Test::More' => 0, 'Test::NoWarnings' => 0, }, 'resources' => { 'homepage' => 'http://search.cpan.org/dist/Graphics-ColorNames-WWW', 'repository' => 'http://github.com/cfaerber/Graphics-ColorNames-WWW', }, ); $b->create_build_script; diff --git a/Changes b/Changes index 39d46b8..8b00302 100644 --- a/Changes +++ b/Changes @@ -1,21 +1,26 @@ Revision history for Perl extension Graphics::ColorNames::WWW +1.12 Thu Dec 17 00:00:00 2009 + - only use ASCII in POD, fixes FAILs with perl 5.6.x + - add examples in eg/ + - FIX: #52870 Depending on itself (reported by ANDK) + 1.11 Tue Dec 14 00:00:00 2009 - switch to Module::Build - fixes FAILures during make test 1.10 Fri Dec 11 00:00:00 2009 - added Graphics::ColorNames::CSS - re-organisation and cleanup - updated Makefile.PL - added LICENSE, SIGNATURE - use Test::More and Test::NoWarnings - move to Github 1.00 Fri Sep 12 00:00:00 2008 - cleanup 0.01 Sat Nov 26 00:00:00 2005 - first public release diff --git a/MANIFEST b/MANIFEST index 1efa281..099fee3 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,22 +1,20 @@ README Changes -LICENSE MANIFEST Build.PL Makefile.PL lib/Graphics/ColorNames/CSS.pm lib/Graphics/ColorNames/IE.pm lib/Graphics/ColorNames/SVG.pm lib/Graphics/ColorNames/WWW.pm t/10pod.t t/11pod_cover.t t/CSS.t t/IExplore.t t/SVG.t t/WWW.t t/WWW_CSS.t t/WWW_HTML.t t/WWW_IExplore.t t/WWW_Mozilla.t t/WWW_SVG.t -META.yml diff --git a/README b/README index 4632374..85e8196 100644 --- a/README +++ b/README @@ -1,34 +1,34 @@ Graphics::ColorNames::WWW The "Graphics:ColorNames::WWW" module provides the full list of color names from various Web specifications and implementations. INSTALLATION To install this module type the following: perl Makefile.PL make make test make install DEPENDENCIES This module requires these other modules and libraries: - Graphics::ColorNames AUTHOR Claus Färber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. LICENSE - Copyright © 2005-2008 Claus Färber. + Copyright © 2005-2009 Claus Färber. Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. diff --git a/lib/Graphics/ColorNames/CSS.pm b/lib/Graphics/ColorNames/CSS.pm index d29e744..c4076f6 100644 --- a/lib/Graphics/ColorNames/CSS.pm +++ b/lib/Graphics/ColorNames/CSS.pm @@ -1,48 +1,46 @@ package Graphics::ColorNames::CSS; require 5.006; use strict; use warnings; use Graphics::ColorNames::WWW(); -our $VERSION = '1.10'; +our $VERSION = '1.12'; *NamesRgbTable = \&Graphics::ColorNames::WWW::NamesRgbTable; 1; -=encoding utf8 - =head1 NAME Graphics::ColorNames::CSS - CSS color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::CSS; $NameTable = Graphics::ColorNames::CSS->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from the CSS Color Module Level 3 Working Draft (2008-07-21). It is actually an alias for L<Graphic::ColorNames::WWW>. This may change in the future should the specs happen to diverge. =head1 AUTHOR -Claus Färber <CFAERBER@cpan.org> +Claus FE<auml>rber <CFAERBER@cpan.org> =head1 LICENSE -Copyright © 2005-2009 Claus Färber. All rights reserved. +Copyright 2005-2009 Claus FE<auml>rber. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Graphics/ColorNames/IE.pm b/lib/Graphics/ColorNames/IE.pm index a755323..85f5008 100644 --- a/lib/Graphics/ColorNames/IE.pm +++ b/lib/Graphics/ColorNames/IE.pm @@ -1,200 +1,198 @@ package Graphics::ColorNames::IE; require 5.006; use strict; use warnings; -our $VERSION = '1.10'; +our $VERSION = '1.12'; sub NamesRgbTable() { use integer; return { (lc 'AliceBlue') => 0xF0F8FF, # 240,248,255 (lc 'AntiqueWhite') => 0xFAEBD7, # 250,235,215 (lc 'Aqua') => 0x00FFFF, # 0,255,255 (lc 'Aquamarine') => 0x7FFFD4, # 127,255,212 (lc 'Azure') => 0xF0FFFF, # 240,255,255 (lc 'Beige') => 0xF5F5DC, # 245,245,220 (lc 'Bisque') => 0xFFE4C4, # 255,228,196 (lc 'Black') => 0x000000, # 0,0,0 (lc 'BlanchedAlmond') => 0xFFEBCD, # 255,235,205 (lc 'Blue') => 0x0000FF, # 0,0,255 (lc 'BlueViolet') => 0x8A2BE2, # 138,43,226 (lc 'Brown') => 0xA52A2A, # 165,42,42 (lc 'BurlyWood') => 0xDEB887, # 222,184,135 (lc 'CadetBlue') => 0x5F9EA0, # 95,158,160 (lc 'Chartreuse') => 0x7FFF00, # 127,255,0 (lc 'Chocolate') => 0xD2691E, # 210,105,30 (lc 'Coral') => 0xFF7F50, # 255,127,80 (lc 'CornflowerBlue') => 0x6495ED, # 100,149,237 (lc 'Cornsilk') => 0xFFF8DC, # 255,248,220 (lc 'Crimson') => 0xDC143C, # 220,20,60 (lc 'Cyan') => 0x00FFFF, # 0,255,255 (lc 'DarkBlue') => 0x00008B, # 0,0,139 (lc 'DarkCyan') => 0x008B8B, # 0,139,139 (lc 'DarkGoldenrod') => 0xB8860B, # 184,134,11 (lc 'DarkGray') => 0xA9A9A9, # 169,169,169 (lc 'DarkGreen') => 0x006400, # 0,100,0 (lc 'DarkKhaki') => 0xBDB76B, # 189,183,107 (lc 'DarkMagenta') => 0x8B008B, # 139,0,139 (lc 'DarkOliveGreen') => 0x556B2F, # 85,107,47 (lc 'DarkOrange') => 0xFF8C00, # 255,140,0 (lc 'DarkOrchid') => 0x9932CC, # 153,50,204 (lc 'DarkRed') => 0x8B0000, # 139,0,0 (lc 'DarkSalmon') => 0xE9967A, # 233,150,122 (lc 'DarkSeaGreen') => 0x8FBC8F, # 143,188,143 (lc 'DarkSlateBlue') => 0x483D8B, # 72,61,139 (lc 'DarkSlateGray') => 0x2F4F4F, # 47,79,79 (lc 'DarkTurquoise') => 0x00CED1, # 0,206,209 (lc 'DarkViolet') => 0x9400D3, # 148,0,211 (lc 'DeepPink') => 0xFF1493, # 255,20,147 (lc 'DeepSkyBlue') => 0x00BFFF, # 0,191,255 (lc 'DimGray') => 0x696969, # 105,105,105 (lc 'DodgerBlue') => 0x1E90FF, # 30,144,255 (lc 'FireBrick') => 0xB22222, # 178,34,34 (lc 'FloralWhite') => 0xFFFAF0, # 255,250,240 (lc 'ForestGreen') => 0x228B22, # 34,139,34 (lc 'Fuchsia') => 0xFF00FF, # 255,0,255 (lc 'Gainsboro') => 0xDCDCDC, # 220,220,220 (lc 'GhostWhite') => 0xF8F8FF, # 248,248,255 (lc 'Gold') => 0xFFD700, # 255,215,0 (lc 'Goldenrod') => 0xDAA520, # 218,165,32 (lc 'Gray') => 0x808080, # 128,128,128 (lc 'Green') => 0x008000, # 0,128,0 (lc 'GreenYellow') => 0xADFF2F, # 173,255,47 (lc 'Honeydew') => 0xF0FFF0, # 240,255,240 (lc 'HotPink') => 0xFF69B4, # 255,105,180 (lc 'IndianRed') => 0xCD5C5C, # 205,92,92 (lc 'Indigo') => 0x4B0082, # 75,0,130 (lc 'Ivory') => 0xFFFFF0, # 255,255,240 (lc 'Khaki') => 0xF0E68C, # 240,230,140 (lc 'Lavender') => 0xE6E6FA, # 230,230,250 (lc 'LavenderBlush') => 0xFFF0F5, # 255,240,245 (lc 'LawnGreen') => 0x7CFC00, # 124,252,0 (lc 'LemonChiffon') => 0xFFFACD, # 255,250,205 (lc 'LightBlue') => 0xADD8E6, # 173,216,230 (lc 'LightCoral') => 0xF08080, # 240,128,128 (lc 'LightCyan') => 0xE0FFFF, # 224,255,255 (lc 'LightGoldenrodYellow') => 0xFAFAD2, # 250,250,210 (lc 'LightGreen') => 0x90EE90, # 144,238,144 (lc 'LightGrey') => 0xD3D3D3, # 211,211,211 (lc 'LightPink') => 0xFFB6C1, # 255,182,193 (lc 'LightSalmon') => 0xFFA07A, # 255,160,122 (lc 'LightSeaGreen') => 0x20B2AA, # 32,178,170 (lc 'LightSkyBlue') => 0x87CEFA, # 135,206,250 (lc 'LightSlateGray') => 0x778899, # 119,136,153 (lc 'LightSteelBlue') => 0xB0C4DE, # 176,196,222 (lc 'LightYellow') => 0xFFFFE0, # 255,255,224 (lc 'Lime') => 0x00FF00, # 0,255,0 (lc 'LimeGreen') => 0x32CD32, # 50,205,50 (lc 'Linen') => 0xFAF0E6, # 250,240,230 (lc 'Magenta') => 0xFF00FF, # 255,0,255 (lc 'Maroon') => 0x800000, # 128,0,0 (lc 'MediumAquamarine') => 0x66CDAA, # 102,205,170 (lc 'MediumBlue') => 0x0000CD, # 0,0,205 (lc 'MediumOrchid') => 0xBA55D3, # 186,85,211 (lc 'MediumPurple') => 0x9370DB, # 147,112,219 (lc 'MediumSeaGreen') => 0x3CB371, # 60,179,113 (lc 'MediumSlateBlue') => 0x7B68EE, # 123,104,238 (lc 'MediumSpringGreen') => 0x00FA9A, # 0,250,154 (lc 'MediumTurquoise') => 0x48D1CC, # 72,209,204 (lc 'MediumVioletRed') => 0xC71585, # 199,21,133 (lc 'MidnightBlue') => 0x191970, # 25,25,112 (lc 'MintCream') => 0xF5FFFA, # 245,255,250 (lc 'MistyRose') => 0xFFE4E1, # 255,228,225 (lc 'Moccasin') => 0xFFE4B5, # 255,228,181 (lc 'NavajoWhite') => 0xFFDEAD, # 255,222,173 (lc 'Navy') => 0x000080, # 0,0,128 (lc 'OldLace') => 0xFDF5E6, # 253,245,230 (lc 'Olive') => 0x808000, # 128,128,0 (lc 'OliveDrab') => 0x6B8E23, # 107,142,35 (lc 'Orange') => 0xFFA500, # 255,165,0 (lc 'OrangeRed') => 0xFF4500, # 255,69,0 (lc 'Orchid') => 0xDA70D6, # 218,112,214 (lc 'PaleGoldenrod') => 0xEEE8AA, # 238,232,170 (lc 'PaleGreen') => 0x98FB98, # 152,251,152 (lc 'PaleTurquoise') => 0xAFEEEE, # 175,238,238 (lc 'PaleVioletRed') => 0xDB7093, # 219,112,147 (lc 'PapayaWhip') => 0xFFEFD5, # 255,239,213 (lc 'PeachPuff') => 0xFFDAB9, # 255,218,185 (lc 'Peru') => 0xCD853F, # 205,133,63 (lc 'Pink') => 0xFFC0CB, # 255,192,203 (lc 'Plum') => 0xDDA0DD, # 221,160,221 (lc 'PowderBlue') => 0xB0E0E6, # 176,224,230 (lc 'Purple') => 0x800080, # 128,0,128 (lc 'Red') => 0xFF0000, # 255,0,0 (lc 'RosyBrown') => 0xBC8F8F, # 188,143,143 (lc 'RoyalBlue') => 0x4169E1, # 65,105,225 (lc 'SaddleBrown') => 0x8B4513, # 139,69,19 (lc 'Salmon') => 0xFA8072, # 250,128,114 (lc 'SandyBrown') => 0xF4A460, # 244,164,96 (lc 'SeaGreen') => 0x2E8B57, # 46,139,87 (lc 'Seashell') => 0xFFF5EE, # 255,245,238 (lc 'Sienna') => 0xA0522D, # 160,82,45 (lc 'Silver') => 0xC0C0C0, # 192,192,192 (lc 'SkyBlue') => 0x87CEEB, # 135,206,235 (lc 'SlateBlue') => 0x6A5ACD, # 106,90,205 (lc 'SlateGray') => 0x708090, # 112,128,144 (lc 'Snow') => 0xFFFAFA, # 255,250,250 (lc 'SpringGreen') => 0x00FF7F, # 0,255,127 (lc 'SteelBlue') => 0x4682B4, # 70,130,180 (lc 'Tan') => 0xD2B48C, # 210,180,140 (lc 'Teal') => 0x008080, # 0,128,128 (lc 'Thistle') => 0xD8BFD8, # 216,191,216 (lc 'Tomato') => 0xFF6347, # 255,99,71 (lc 'Turquoise') => 0x40E0D0, # 64,224,208 (lc 'Violet') => 0xEE82EE, # 238,130,238 (lc 'Wheat') => 0xF5DEB3, # 245,222,179 (lc 'White') => 0xFFFFFF, # 255,255,255 (lc 'WhiteSmoke') => 0xF5F5F5, # 245,245,245 (lc 'Yellow') => 0xFFFF00, # 255,255,0 (lc 'YellowGreen') => 0x9ACD32, # 154,205,50 }; } 1; -=encoding utf8 - =head1 NAME Graphics::ColorNames::IE - MS Internet Explorer color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::IE; $NameTable = Graphics::ColorNames::IE->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values recognized by Microsoft Internet Explorer. =head2 NOTE Although Microsoft calls them "X11 color names", some of them are not identical to the definitions in the X Specification. =head1 SEE ALSO C<Graphics::ColorNames>, MSDN <http://msdn.microsoft.com/library/en-us/dnwebgen/html/X11_names.asp> =head1 AUTHOR -Claus Färber <CFAERBER@cpan.org> +Claus FE<auml>rber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. =head1 LICENSE -Copyright © 2005-2009 Claus Färber. +Copyright 2005-2009 Claus FE<auml>rber. -Copyright © 2001-2004 Robert Rothenberg. +Copyright 2001-2004 Robert Rothenberg. -All rights reserved. This program is free software; you can redistribute it +This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Graphics/ColorNames/SVG.pm b/lib/Graphics/ColorNames/SVG.pm index 30a3334..4ae6589 100644 --- a/lib/Graphics/ColorNames/SVG.pm +++ b/lib/Graphics/ColorNames/SVG.pm @@ -1,49 +1,47 @@ package Graphics::ColorNames::SVG; require 5.006; use strict; use warnings; use Graphics::ColorNames::WWW(); -our $VERSION = '1.10'; +our $VERSION = '1.12'; *NamesRgbTable = \&Graphics::ColorNames::WWW::NamesRgbTable; 1; -=encoding utf8 - =head1 NAME Graphics::ColorNames::SVG - SVG color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::SVG; $NameTable = Graphics::ColorNames::SVG->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from the SVG 1.2 Specification. It is actually an alias for L<Graphic::ColorNames::WWW>. This may change should the specs happen to diverge. =head1 AUTHOR -Claus Färber <CFAERBER@cpan.org> +Claus FE<auml>rber <CFAERBER@cpan.org> =head1 LICENSE -Copyright © 2008-2009 Claus Färber. +Copyright 2008-2009 Claus FE<auml>rber. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Graphics/ColorNames/WWW.pm b/lib/Graphics/ColorNames/WWW.pm index 3f02593..3358573 100644 --- a/lib/Graphics/ColorNames/WWW.pm +++ b/lib/Graphics/ColorNames/WWW.pm @@ -1,214 +1,212 @@ package Graphics::ColorNames::WWW; require 5.006; use strict; use warnings; -our $VERSION = '1.11'; +our $VERSION = '1.12'; sub NamesRgbTable() { sub rgb { ($_[0] << 16) + ($_[1] << 8) + ($_[2]) } use integer; return { 'aliceblue' => rgb(240, 248, 255), 'antiquewhite' => rgb(250, 235, 215), 'aqua' => rgb( 0, 255, 255), 'aquamarine' => rgb(127, 255, 212), 'azure' => rgb(240, 255, 255), 'beige' => rgb(245, 245, 220), 'bisque' => rgb(255, 228, 196), 'black' => rgb( 0, 0, 0), 'blanchedalmond' => rgb(255, 235, 205), 'blue' => rgb( 0, 0, 255), 'blueviolet' => rgb(138, 43, 226), 'brown' => rgb(165, 42, 42), 'burlywood' => rgb(222, 184, 135), 'cadetblue' => rgb( 95, 158, 160), 'chartreuse' => rgb(127, 255, 0), 'chocolate' => rgb(210, 105, 30), 'coral' => rgb(255, 127, 80), 'cornflowerblue' => rgb(100, 149, 237), 'cornsilk' => rgb(255, 248, 220), 'crimson' => rgb(220, 20, 60), 'cyan' => rgb( 0, 255, 255), 'darkblue' => rgb( 0, 0, 139), 'darkcyan' => rgb( 0, 139, 139), 'darkgoldenrod' => rgb(184, 134, 11), 'darkgray' => rgb(169, 169, 169), 'darkgreen' => rgb( 0, 100, 0), 'darkgrey' => rgb(169, 169, 169), 'darkkhaki' => rgb(189, 183, 107), 'darkmagenta' => rgb(139, 0, 139), 'darkolivegreen' => rgb( 85, 107, 47), 'darkorange' => rgb(255, 140, 0), 'darkorchid' => rgb(153, 50, 204), 'darkred' => rgb(139, 0, 0), 'darksalmon' => rgb(233, 150, 122), 'darkseagreen' => rgb(143, 188, 143), 'darkslateblue' => rgb( 72, 61, 139), 'darkslategray' => rgb( 47, 79, 79), 'darkslategrey' => rgb( 47, 79, 79), 'darkturquoise' => rgb( 0, 206, 209), 'darkviolet' => rgb(148, 0, 211), 'deeppink' => rgb(255, 20, 147), 'deepskyblue' => rgb( 0, 191, 255), 'dimgray' => rgb(105, 105, 105), 'dimgrey' => rgb(105, 105, 105), 'dodgerblue' => rgb( 30, 144, 255), 'firebrick' => rgb(178, 34, 34), 'floralwhite' => rgb(255, 250, 240), 'forestgreen' => rgb( 34, 139, 34), 'fuchsia' => 0xff00ff, # "fuscia" is incorrect but common 'fuscia' => 0xff00ff, # mis-spelling... 'gainsboro' => rgb(220, 220, 220), 'ghostwhite' => rgb(248, 248, 255), 'gold' => rgb(255, 215, 0), 'goldenrod' => rgb(218, 165, 32), 'gray' => rgb(128, 128, 128), 'grey' => rgb(128, 128, 128), 'green' => rgb( 0, 128, 0), 'greenyellow' => rgb(173, 255, 47), 'honeydew' => rgb(240, 255, 240), 'hotpink' => rgb(255, 105, 180), 'indianred' => rgb(205, 92, 92), 'indigo' => rgb( 75, 0, 130), 'ivory' => rgb(255, 255, 240), 'khaki' => rgb(240, 230, 140), 'lavender' => rgb(230, 230, 250), 'lavenderblush' => rgb(255, 240, 245), 'lawngreen' => rgb(124, 252, 0), 'lemonchiffon' => rgb(255, 250, 205), 'lightblue' => rgb(173, 216, 230), 'lightcoral' => rgb(240, 128, 128), 'lightcyan' => rgb(224, 255, 255), 'lightgoldenrodyellow' => rgb(250, 250, 210), 'lightgray' => rgb(211, 211, 211), 'lightgreen' => rgb(144, 238, 144), 'lightgrey' => rgb(211, 211, 211), 'lightpink' => rgb(255, 182, 193), 'lightsalmon' => rgb(255, 160, 122), 'lightseagreen' => rgb( 32, 178, 170), 'lightskyblue' => rgb(135, 206, 250), 'lightslategray' => rgb(119, 136, 153), 'lightslategrey' => rgb(119, 136, 153), 'lightsteelblue' => rgb(176, 196, 222), 'lightyellow' => rgb(255, 255, 224), 'lime' => rgb( 0, 255, 0), 'limegreen' => rgb( 50, 205, 50), 'linen' => rgb(250, 240, 230), 'magenta' => rgb(255, 0, 255), 'maroon' => rgb(128, 0, 0), 'mediumaquamarine' => rgb(102, 205, 170), 'mediumblue' => rgb( 0, 0, 205), 'mediumorchid' => rgb(186, 85, 211), 'mediumpurple' => rgb(147, 112, 219), 'mediumseagreen' => rgb( 60, 179, 113), 'mediumslateblue' => rgb(123, 104, 238), 'mediumspringgreen' => rgb( 0, 250, 154), 'mediumturquoise' => rgb( 72, 209, 204), 'mediumvioletred' => rgb(199, 21, 133), 'midnightblue' => rgb( 25, 25, 112), 'mintcream' => rgb(245, 255, 250), 'mistyrose' => rgb(255, 228, 225), 'moccasin' => rgb(255, 228, 181), 'navajowhite' => rgb(255, 222, 173), 'navy' => rgb( 0, 0, 128), 'oldlace' => rgb(253, 245, 230), 'olive' => rgb(128, 128, 0), 'olivedrab' => rgb(107, 142, 35), 'orange' => rgb(255, 165, 0), 'orangered' => rgb(255, 69, 0), 'orchid' => rgb(218, 112, 214), 'palegoldenrod' => rgb(238, 232, 170), 'palegreen' => rgb(152, 251, 152), 'paleturquoise' => rgb(175, 238, 238), 'palevioletred' => rgb(219, 112, 147), 'papayawhip' => rgb(255, 239, 213), 'peachpuff' => rgb(255, 218, 185), 'peru' => rgb(205, 133, 63), 'pink' => rgb(255, 192, 203), 'plum' => rgb(221, 160, 221), 'powderblue' => rgb(176, 224, 230), 'purple' => rgb(128, 0, 128), 'red' => rgb(255, 0, 0), 'rosybrown' => rgb(188, 143, 143), 'royalblue' => rgb( 65, 105, 225), 'saddlebrown' => rgb(139, 69, 19), 'salmon' => rgb(250, 128, 114), 'sandybrown' => rgb(244, 164, 96), 'seagreen' => rgb( 46, 139, 87), 'seashell' => rgb(255, 245, 238), 'sienna' => rgb(160, 82, 45), 'silver' => rgb(192, 192, 192), 'skyblue' => rgb(135, 206, 235), 'slateblue' => rgb(106, 90, 205), 'slategray' => rgb(112, 128, 144), 'slategrey' => rgb(112, 128, 144), 'snow' => rgb(255, 250, 250), 'springgreen' => rgb( 0, 255, 127), 'steelblue' => rgb( 70, 130, 180), 'tan' => rgb(210, 180, 140), 'teal' => rgb( 0, 128, 128), 'thistle' => rgb(216, 191, 216), 'tomato' => rgb(255, 99, 71), 'turquoise' => rgb( 64, 224, 208), 'violet' => rgb(238, 130, 238), 'wheat' => rgb(245, 222, 179), 'white' => rgb(255, 255, 255), 'whitesmoke' => rgb(245, 245, 245), 'yellow' => rgb(255, 255, 0), 'yellowgreen' => rgb(154, 205, 50), }; } 1; -=encoding utf8 - =head1 NAME Graphics::ColorNames::WWW - WWW color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::WWW; $NameTable = Graphics::ColorNames::WWW->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from various WWW specifications, such as SVG or CSS. =head2 NOTE Reportedly "fuchsia" was misspelled "fuscia" in an unidentified HTML specification. It also appears to be a common misspelling, so both names are recognized. =head1 SEE ALSO C<Graphics::ColorNames>, SVG 1.2 Specificiation <http://www.w3.org/SVG/>, CSS Color Module Level 3 <http://www.w3.org/TR/css3-color>. =head1 AUTHOR -Claus Färber <CFAERBER@cpan.org> +Claus FE<auml>rber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. =head1 LICENSE -Copyright © 2005-2009 Claus Färber. +Copyright 2005-2009 Claus FE<auml>rber. -Copyright © 2001-2004 Robert Rothenberg. +Copyright 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
cfaerber/Graphics-ColorNames-WWW
f14a4b573a53161a0c4c50a3594cf960d808f350
add examples in eg/
diff --git a/eg/pink_hex.pl b/eg/pink_hex.pl new file mode 100644 index 0000000..521686f --- /dev/null +++ b/eg/pink_hex.pl @@ -0,0 +1,10 @@ +#!/usr/bin/perl + +use strict; +use utf8; + +use Graphics::ColorNames; + +my $colors = new Graphics::ColorNames('WWW'); + +print "pink: ", $colors->hex('pink'), "\n"; diff --git a/eg/pink_tie.pl b/eg/pink_tie.pl new file mode 100644 index 0000000..0712c1e --- /dev/null +++ b/eg/pink_tie.pl @@ -0,0 +1,10 @@ +#!/usr/bin/perl + +use strict; +use utf8; + +use Graphics::ColorNames; + +tie my %colors, 'Graphics::ColorNames', 'WWW'; + +print "pink: ", $colors{'pink'}, "\n";
cfaerber/Graphics-ColorNames-WWW
3c1d1c048b115d8b6b12cbf4fca2c5c610bf9594
new version 1.11, switch to Module::Build, fixes FAILures during make test
diff --git a/.gitignore b/.gitignore index 0409a5f..e3276bd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,11 @@ -Makefile -Makefile.old -blib +Build Graphics-* +LICENSE META.yml +Makefile +Makefile.PL +Makefile.old SIGNATURE +_build +blib pm_to_blib diff --git a/Build.PL b/Build.PL new file mode 100644 index 0000000..4d09616 --- /dev/null +++ b/Build.PL @@ -0,0 +1,31 @@ +#!/usr/bin/perl + +use 5.006; +use strict; + +use Module::Build; + +my $b = Module::Build->new( + 'module_name' => 'Graphics::ColorNames::WWW', + 'license' => 'perl', + + 'sign' => 1, + 'create_license' => 1, + 'create_makefile_pl' => 'traditional', + + 'requires' => { + 'Graphics::ColorNames' => 0.32, + 'Graphics::ColorNames::WWW' => 0.01, + 'Params::Validate' => 0.75, + }, + 'build_requires' => { + 'Test::More' => 0, + 'Test::NoWarnings' => 0, + }, + 'resources' => { + 'homepage' => 'http://search.cpan.org/dist/Graphics-ColorNames-WWW', + 'repository' => 'http://github.com/cfaerber/Graphics-ColorNames-WWW', + }, +); + +$b->create_build_script; diff --git a/Changes b/Changes index 79f689e..39d46b8 100644 --- a/Changes +++ b/Changes @@ -1,17 +1,21 @@ Revision history for Perl extension Graphics::ColorNames::WWW +1.11 Tue Dec 14 00:00:00 2009 + - switch to Module::Build + - fixes FAILures during make test + 1.10 Fri Dec 11 00:00:00 2009 - added Graphics::ColorNames::CSS - re-organisation and cleanup - updated Makefile.PL - added LICENSE, SIGNATURE - use Test::More and Test::NoWarnings - move to Github 1.00 Fri Sep 12 00:00:00 2008 - cleanup 0.01 Sat Nov 26 00:00:00 2005 - first public release diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 9d0305b..0000000 --- a/LICENSE +++ /dev/null @@ -1,383 +0,0 @@ -Terms of Perl itself - -a) the GNU General Public License as published by the Free - Software Foundation; either version 1, or (at your option) any - later version, or -b) the "Artistic License" - ---------------------------------------------------------------------------- - -The General Public License (GPL) -Version 2, June 1991 - -Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, -Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute -verbatim copies of this license document, but changing it is not allowed. - -Preamble - -The licenses for most software are designed to take away your freedom to share -and change it. By contrast, the GNU General Public License is intended to -guarantee your freedom to share and change free software--to make sure the -software is free for all its users. This General Public License applies to most of -the Free Software Foundation's software and to any other program whose -authors commit to using it. (Some other Free Software Foundation software is -covered by the GNU Library General Public License instead.) You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our -General Public Licenses are designed to make sure that you have the freedom -to distribute copies of free software (and charge for this service if you wish), that -you receive source code or can get it if you want it, that you can change the -software or use pieces of it in new free programs; and that you know you can do -these things. - -To protect your rights, we need to make restrictions that forbid anyone to deny -you these rights or to ask you to surrender the rights. These restrictions -translate to certain responsibilities for you if you distribute copies of the -software, or if you modify it. - -For example, if you distribute copies of such a program, whether gratis or for a -fee, you must give the recipients all the rights that you have. You must make -sure that they, too, receive or can get the source code. And you must show -them these terms so they know their rights. - -We protect your rights with two steps: (1) copyright the software, and (2) offer -you this license which gives you legal permission to copy, distribute and/or -modify the software. - -Also, for each author's protection and ours, we want to make certain that -everyone understands that there is no warranty for this free software. If the -software is modified by someone else and passed on, we want its recipients to -know that what they have is not the original, so that any problems introduced by -others will not reflect on the original authors' reputations. - -Finally, any free program is threatened constantly by software patents. We wish -to avoid the danger that redistributors of a free program will individually obtain -patent licenses, in effect making the program proprietary. To prevent this, we -have made it clear that any patent must be licensed for everyone's free use or -not licensed at all. - -The precise terms and conditions for copying, distribution and modification -follow. - -GNU GENERAL PUBLIC LICENSE -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND -MODIFICATION - -0. This License applies to any program or other work which contains a notice -placed by the copyright holder saying it may be distributed under the terms of -this General Public License. The "Program", below, refers to any such program -or work, and a "work based on the Program" means either the Program or any -derivative work under copyright law: that is to say, a work containing the -Program or a portion of it, either verbatim or with modifications and/or translated -into another language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not covered by -this License; they are outside its scope. The act of running the Program is not -restricted, and the output from the Program is covered only if its contents -constitute a work based on the Program (independent of having been made by -running the Program). Whether that is true depends on what the Program does. - -1. You may copy and distribute verbatim copies of the Program's source code as -you receive it, in any medium, provided that you conspicuously and appropriately -publish on each copy an appropriate copyright notice and disclaimer of warranty; -keep intact all the notices that refer to this License and to the absence of any -warranty; and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and you may at -your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Program or any portion of it, thus -forming a work based on the Program, and copy and distribute such -modifications or work under the terms of Section 1 above, provided that you also -meet all of these conditions: - -a) You must cause the modified files to carry prominent notices stating that you -changed the files and the date of any change. - -b) You must cause any work that you distribute or publish, that in whole or in -part contains or is derived from the Program or any part thereof, to be licensed -as a whole at no charge to all third parties under the terms of this License. - -c) If the modified program normally reads commands interactively when run, you -must cause it, when started running for such interactive use in the most ordinary -way, to print or display an announcement including an appropriate copyright -notice and a notice that there is no warranty (or else, saying that you provide a -warranty) and that users may redistribute the program under these conditions, -and telling the user how to view a copy of this License. (Exception: if the -Program itself is interactive but does not normally print such an announcement, -your work based on the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If identifiable -sections of that work are not derived from the Program, and can be reasonably -considered independent and separate works in themselves, then this License, -and its terms, do not apply to those sections when you distribute them as -separate works. But when you distribute the same sections as part of a whole -which is a work based on the Program, the distribution of the whole must be on -the terms of this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your rights to -work written entirely by you; rather, the intent is to exercise the right to control -the distribution of derivative or collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program with the -Program (or with a work based on the Program) on a volume of a storage or -distribution medium does not bring the other work under the scope of this -License. - -3. You may copy and distribute the Program (or a work based on it, under -Section 2) in object code or executable form under the terms of Sections 1 and 2 -above provided that you also do one of the following: - -a) Accompany it with the complete corresponding machine-readable source -code, which must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange; or, - -b) Accompany it with a written offer, valid for at least three years, to give any -third party, for a charge no more than your cost of physically performing source -distribution, a complete machine-readable copy of the corresponding source -code, to be distributed under the terms of Sections 1 and 2 above on a medium -customarily used for software interchange; or, - -c) Accompany it with the information you received as to the offer to distribute -corresponding source code. (This alternative is allowed only for noncommercial -distribution and only if you received the program in object code or executable -form with such an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for making -modifications to it. For an executable work, complete source code means all the -source code for all modules it contains, plus any associated interface definition -files, plus the scripts used to control compilation and installation of the -executable. However, as a special exception, the source code distributed need -not include anything that is normally distributed (in either source or binary form) -with the major components (compiler, kernel, and so on) of the operating system -on which the executable runs, unless that component itself accompanies the -executable. - -If distribution of executable or object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the source -code from the same place counts as distribution of the source code, even though -third parties are not compelled to copy the source along with the object code. - -4. You may not copy, modify, sublicense, or distribute the Program except as -expressly provided under this License. Any attempt otherwise to copy, modify, -sublicense or distribute the Program is void, and will automatically terminate -your rights under this License. However, parties who have received copies, or -rights, from you under this License will not have their licenses terminated so long -as such parties remain in full compliance. - -5. You are not required to accept this License, since you have not signed it. -However, nothing else grants you permission to modify or distribute the Program -or its derivative works. These actions are prohibited by law if you do not accept -this License. Therefore, by modifying or distributing the Program (or any work -based on the Program), you indicate your acceptance of this License to do so, -and all its terms and conditions for copying, distributing or modifying the -Program or works based on it. - -6. Each time you redistribute the Program (or any work based on the Program), -the recipient automatically receives a license from the original licensor to copy, -distribute or modify the Program subject to these terms and conditions. You -may not impose any further restrictions on the recipients' exercise of the rights -granted herein. You are not responsible for enforcing compliance by third parties -to this License. - -7. If, as a consequence of a court judgment or allegation of patent infringement -or for any other reason (not limited to patent issues), conditions are imposed on -you (whether by court order, agreement or otherwise) that contradict the -conditions of this License, they do not excuse you from the conditions of this -License. If you cannot distribute so as to satisfy simultaneously your obligations -under this License and any other pertinent obligations, then as a consequence -you may not distribute the Program at all. For example, if a patent license would -not permit royalty-free redistribution of the Program by all those who receive -copies directly or indirectly through you, then the only way you could satisfy -both it and this License would be to refrain entirely from distribution of the -Program. - -If any portion of this section is held invalid or unenforceable under any particular -circumstance, the balance of the section is intended to apply and the section as -a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other -property right claims or to contest validity of any such claims; this section has -the sole purpose of protecting the integrity of the free software distribution -system, which is implemented by public license practices. Many people have -made generous contributions to the wide range of software distributed through -that system in reliance on consistent application of that system; it is up to the -author/donor to decide if he or she is willing to distribute software through any -other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a -consequence of the rest of this License. - -8. If the distribution and/or use of the Program is restricted in certain countries -either by patents or by copyrighted interfaces, the original copyright holder who -places the Program under this License may add an explicit geographical -distribution limitation excluding those countries, so that distribution is permitted -only in or among countries not thus excluded. In such case, this License -incorporates the limitation as if written in the body of this License. - -9. The Free Software Foundation may publish revised and/or new versions of the -General Public License from time to time. Such new versions will be similar in -spirit to the present version, but may differ in detail to address new problems or -concerns. - -Each version is given a distinguishing version number. If the Program specifies a -version number of this License which applies to it and "any later version", you -have the option of following the terms and conditions either of that version or of -any later version published by the Free Software Foundation. If the Program does -not specify a version number of this License, you may choose any version ever -published by the Free Software Foundation. - -10. If you wish to incorporate parts of the Program into other free programs -whose distribution conditions are different, write to the author to ask for -permission. For software which is copyrighted by the Free Software Foundation, -write to the Free Software Foundation; we sometimes make exceptions for this. -Our decision will be guided by the two goals of preserving the free status of all -derivatives of our free software and of promoting the sharing and reuse of -software generally. - -NO WARRANTY - -11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS -NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE -COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM -"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR -IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE -ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, -YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR -CORRECTION. - -12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED -TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY -WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS -PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES -ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM -(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY -OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS -BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -END OF TERMS AND CONDITIONS - - ---------------------------------------------------------------------------- - -The Artistic License - -Preamble - -The intent of this document is to state the conditions under which a Package -may be copied, such that the Copyright Holder maintains some semblance of -artistic control over the development of the package, while giving the users of the -package the right to use and distribute the Package in a more-or-less customary -fashion, plus the right to make reasonable modifications. - -Definitions: - -- "Package" refers to the collection of files distributed by the Copyright - Holder, and derivatives of that collection of files created through textual - modification. -- "Standard Version" refers to such a Package if it has not been modified, - or has been modified in accordance with the wishes of the Copyright - Holder. -- "Copyright Holder" is whoever is named in the copyright or copyrights for - the package. -- "You" is you, if you're thinking about copying or distributing this Package. -- "Reasonable copying fee" is whatever you can justify on the basis of - media cost, duplication charges, time of people involved, and so on. (You - will not be required to justify it to the Copyright Holder, but only to the - computing community at large as a market that must bear the fee.) -- "Freely Available" means that no fee is charged for the item itself, though - there may be fees involved in handling the item. It also means that - recipients of the item may redistribute it under the same conditions they - received it. - -1. You may make and give away verbatim copies of the source form of the -Standard Version of this Package without restriction, provided that you duplicate -all of the original copyright notices and associated disclaimers. - -2. You may apply bug fixes, portability fixes and other modifications derived from -the Public Domain or from the Copyright Holder. A Package modified in such a -way shall still be considered the Standard Version. - -3. You may otherwise modify your copy of this Package in any way, provided -that you insert a prominent notice in each changed file stating how and when -you changed that file, and provided that you do at least ONE of the following: - - a) place your modifications in the Public Domain or otherwise - make them Freely Available, such as by posting said modifications - to Usenet or an equivalent medium, or placing the modifications on - a major archive site such as ftp.uu.net, or by allowing the - Copyright Holder to include your modifications in the Standard - Version of the Package. - - b) use the modified Package only within your corporation or - organization. - - c) rename any non-standard executables so the names do not - conflict with standard executables, which must also be provided, - and provide a separate manual page for each non-standard - executable that clearly documents how it differs from the Standard - Version. - - d) make other distribution arrangements with the Copyright Holder. - -4. You may distribute the programs of this Package in object code or executable -form, provided that you do at least ONE of the following: - - a) distribute a Standard Version of the executables and library - files, together with instructions (in the manual page or equivalent) - on where to get the Standard Version. - - b) accompany the distribution with the machine-readable source of - the Package with your modifications. - - c) accompany any non-standard executables with their - corresponding Standard Version executables, giving the - non-standard executables non-standard names, and clearly - documenting the differences in manual pages (or equivalent), - together with instructions on where to get the Standard Version. - - d) make other distribution arrangements with the Copyright Holder. - -5. You may charge a reasonable copying fee for any distribution of this Package. -You may charge any fee you choose for support of this Package. You may not -charge a fee for this Package itself. However, you may distribute this Package in -aggregate with other (possibly commercial) programs as part of a larger -(possibly commercial) software distribution provided that you do not advertise -this Package as a product of your own. - -6. The scripts and library files supplied as input to or produced as output from -the programs of this Package do not automatically fall under the copyright of this -Package, but belong to whomever generated them, and may be sold -commercially, and may be aggregated with this Package. - -7. C or perl subroutines supplied by you and linked into this Package shall not -be considered part of this Package. - -8. Aggregation of this Package with a commercial distribution is always permitted -provided that the use of this Package is embedded; that is, when no overt attempt -is made to make this Package's interfaces visible to the end user of the -commercial distribution. Such use shall not be construed as a distribution of -this Package. - -9. The name of the Copyright Holder may not be used to endorse or promote -products derived from this software without specific prior written permission. - -10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR -IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED -WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR -PURPOSE. - -The End - - diff --git a/MANIFEST b/MANIFEST index f72b25b..1efa281 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,20 +1,22 @@ README Changes LICENSE MANIFEST +Build.PL Makefile.PL lib/Graphics/ColorNames/CSS.pm lib/Graphics/ColorNames/IE.pm lib/Graphics/ColorNames/SVG.pm lib/Graphics/ColorNames/WWW.pm t/10pod.t t/11pod_cover.t t/CSS.t t/IExplore.t t/SVG.t t/WWW.t t/WWW_CSS.t t/WWW_HTML.t t/WWW_IExplore.t t/WWW_Mozilla.t t/WWW_SVG.t +META.yml diff --git a/Makefile.PL b/Makefile.PL deleted file mode 100644 index 44dfc6e..0000000 --- a/Makefile.PL +++ /dev/null @@ -1,43 +0,0 @@ -use ExtUtils::MakeMaker; - -# See lib/ExtUtils/MakeMaker.pm for details of how to influence -# the contents of the Makefile that is written. -WriteMakefile( - 'NAME' => 'Graphics::ColorNames::WWW', - 'VERSION_FROM' => 'lib/Graphics/ColorNames/WWW.pm', - 'PREREQ_PM' => { - 'Graphics::ColorNames' => 0.32, - }, - -$] < 5.005 ? () : ( - 'ABSTRACT_FROM' => 'lib/Graphics/ColorNames/WWW.pm', - 'AUTHOR' => 'Claus Faerber <CFAERBER@cpan.org>', - 'LICENSE' => 'perl', -), - -$ExtUtils::MakeMaker::VERSION < 6.18 ? () : ( - 'SIGN' => 1, -), - -$ExtUtils::MakeMaker::VERSION < 6.45 ? () : ( - 'META_MERGE' => { - 'build_requires' => { - 'Test::More' => 0, - 'Test::NoWarnings' => 0, - }, - 'resources' => { - 'homepage' => 'http://search.cpan.org/dist/Graphics-ColorNames-WWW', - 'repository' => 'http://github.com/cfaerber/Graphics-ColorNames-WWW', - }, - }, -), -); - -sub MY::postamble { -return <<EOF -release: release-cpan - -release-cpan: - cpan-upload \$(DISTVNAME).tar\$(SUFFIX) -EOF -} diff --git a/README b/README index 0c69975..4632374 100644 --- a/README +++ b/README @@ -1,36 +1,34 @@ Graphics::ColorNames::WWW The "Graphics:ColorNames::WWW" module provides the full list of color names from various Web specifications and implementations. INSTALLATION To install this module type the following: perl Makefile.PL make make test make install DEPENDENCIES This module requires these other modules and libraries: - Graphics::ColorNames AUTHOR Claus Färber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. LICENSE Copyright © 2005-2008 Claus Färber. Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. - -$Id$ diff --git a/lib/Graphics/ColorNames/WWW.pm b/lib/Graphics/ColorNames/WWW.pm index bd6e766..3f02593 100644 --- a/lib/Graphics/ColorNames/WWW.pm +++ b/lib/Graphics/ColorNames/WWW.pm @@ -1,214 +1,214 @@ package Graphics::ColorNames::WWW; require 5.006; use strict; use warnings; -our $VERSION = '1.10'; +our $VERSION = '1.11'; sub NamesRgbTable() { sub rgb { ($_[0] << 16) + ($_[1] << 8) + ($_[2]) } use integer; return { 'aliceblue' => rgb(240, 248, 255), 'antiquewhite' => rgb(250, 235, 215), 'aqua' => rgb( 0, 255, 255), 'aquamarine' => rgb(127, 255, 212), 'azure' => rgb(240, 255, 255), 'beige' => rgb(245, 245, 220), 'bisque' => rgb(255, 228, 196), 'black' => rgb( 0, 0, 0), 'blanchedalmond' => rgb(255, 235, 205), 'blue' => rgb( 0, 0, 255), 'blueviolet' => rgb(138, 43, 226), 'brown' => rgb(165, 42, 42), 'burlywood' => rgb(222, 184, 135), 'cadetblue' => rgb( 95, 158, 160), 'chartreuse' => rgb(127, 255, 0), 'chocolate' => rgb(210, 105, 30), 'coral' => rgb(255, 127, 80), 'cornflowerblue' => rgb(100, 149, 237), 'cornsilk' => rgb(255, 248, 220), 'crimson' => rgb(220, 20, 60), 'cyan' => rgb( 0, 255, 255), 'darkblue' => rgb( 0, 0, 139), 'darkcyan' => rgb( 0, 139, 139), 'darkgoldenrod' => rgb(184, 134, 11), 'darkgray' => rgb(169, 169, 169), 'darkgreen' => rgb( 0, 100, 0), 'darkgrey' => rgb(169, 169, 169), 'darkkhaki' => rgb(189, 183, 107), 'darkmagenta' => rgb(139, 0, 139), 'darkolivegreen' => rgb( 85, 107, 47), 'darkorange' => rgb(255, 140, 0), 'darkorchid' => rgb(153, 50, 204), 'darkred' => rgb(139, 0, 0), 'darksalmon' => rgb(233, 150, 122), 'darkseagreen' => rgb(143, 188, 143), 'darkslateblue' => rgb( 72, 61, 139), 'darkslategray' => rgb( 47, 79, 79), 'darkslategrey' => rgb( 47, 79, 79), 'darkturquoise' => rgb( 0, 206, 209), 'darkviolet' => rgb(148, 0, 211), 'deeppink' => rgb(255, 20, 147), 'deepskyblue' => rgb( 0, 191, 255), 'dimgray' => rgb(105, 105, 105), 'dimgrey' => rgb(105, 105, 105), 'dodgerblue' => rgb( 30, 144, 255), 'firebrick' => rgb(178, 34, 34), 'floralwhite' => rgb(255, 250, 240), 'forestgreen' => rgb( 34, 139, 34), 'fuchsia' => 0xff00ff, # "fuscia" is incorrect but common 'fuscia' => 0xff00ff, # mis-spelling... 'gainsboro' => rgb(220, 220, 220), 'ghostwhite' => rgb(248, 248, 255), 'gold' => rgb(255, 215, 0), 'goldenrod' => rgb(218, 165, 32), 'gray' => rgb(128, 128, 128), 'grey' => rgb(128, 128, 128), 'green' => rgb( 0, 128, 0), 'greenyellow' => rgb(173, 255, 47), 'honeydew' => rgb(240, 255, 240), 'hotpink' => rgb(255, 105, 180), 'indianred' => rgb(205, 92, 92), 'indigo' => rgb( 75, 0, 130), 'ivory' => rgb(255, 255, 240), 'khaki' => rgb(240, 230, 140), 'lavender' => rgb(230, 230, 250), 'lavenderblush' => rgb(255, 240, 245), 'lawngreen' => rgb(124, 252, 0), 'lemonchiffon' => rgb(255, 250, 205), 'lightblue' => rgb(173, 216, 230), 'lightcoral' => rgb(240, 128, 128), 'lightcyan' => rgb(224, 255, 255), 'lightgoldenrodyellow' => rgb(250, 250, 210), 'lightgray' => rgb(211, 211, 211), 'lightgreen' => rgb(144, 238, 144), 'lightgrey' => rgb(211, 211, 211), 'lightpink' => rgb(255, 182, 193), 'lightsalmon' => rgb(255, 160, 122), 'lightseagreen' => rgb( 32, 178, 170), 'lightskyblue' => rgb(135, 206, 250), 'lightslategray' => rgb(119, 136, 153), 'lightslategrey' => rgb(119, 136, 153), 'lightsteelblue' => rgb(176, 196, 222), 'lightyellow' => rgb(255, 255, 224), 'lime' => rgb( 0, 255, 0), 'limegreen' => rgb( 50, 205, 50), 'linen' => rgb(250, 240, 230), 'magenta' => rgb(255, 0, 255), 'maroon' => rgb(128, 0, 0), 'mediumaquamarine' => rgb(102, 205, 170), 'mediumblue' => rgb( 0, 0, 205), 'mediumorchid' => rgb(186, 85, 211), 'mediumpurple' => rgb(147, 112, 219), 'mediumseagreen' => rgb( 60, 179, 113), 'mediumslateblue' => rgb(123, 104, 238), 'mediumspringgreen' => rgb( 0, 250, 154), 'mediumturquoise' => rgb( 72, 209, 204), 'mediumvioletred' => rgb(199, 21, 133), 'midnightblue' => rgb( 25, 25, 112), 'mintcream' => rgb(245, 255, 250), 'mistyrose' => rgb(255, 228, 225), 'moccasin' => rgb(255, 228, 181), 'navajowhite' => rgb(255, 222, 173), 'navy' => rgb( 0, 0, 128), 'oldlace' => rgb(253, 245, 230), 'olive' => rgb(128, 128, 0), 'olivedrab' => rgb(107, 142, 35), 'orange' => rgb(255, 165, 0), 'orangered' => rgb(255, 69, 0), 'orchid' => rgb(218, 112, 214), 'palegoldenrod' => rgb(238, 232, 170), 'palegreen' => rgb(152, 251, 152), 'paleturquoise' => rgb(175, 238, 238), 'palevioletred' => rgb(219, 112, 147), 'papayawhip' => rgb(255, 239, 213), 'peachpuff' => rgb(255, 218, 185), 'peru' => rgb(205, 133, 63), 'pink' => rgb(255, 192, 203), 'plum' => rgb(221, 160, 221), 'powderblue' => rgb(176, 224, 230), 'purple' => rgb(128, 0, 128), 'red' => rgb(255, 0, 0), 'rosybrown' => rgb(188, 143, 143), 'royalblue' => rgb( 65, 105, 225), 'saddlebrown' => rgb(139, 69, 19), 'salmon' => rgb(250, 128, 114), 'sandybrown' => rgb(244, 164, 96), 'seagreen' => rgb( 46, 139, 87), 'seashell' => rgb(255, 245, 238), 'sienna' => rgb(160, 82, 45), 'silver' => rgb(192, 192, 192), 'skyblue' => rgb(135, 206, 235), 'slateblue' => rgb(106, 90, 205), 'slategray' => rgb(112, 128, 144), 'slategrey' => rgb(112, 128, 144), 'snow' => rgb(255, 250, 250), 'springgreen' => rgb( 0, 255, 127), 'steelblue' => rgb( 70, 130, 180), 'tan' => rgb(210, 180, 140), 'teal' => rgb( 0, 128, 128), 'thistle' => rgb(216, 191, 216), 'tomato' => rgb(255, 99, 71), 'turquoise' => rgb( 64, 224, 208), 'violet' => rgb(238, 130, 238), 'wheat' => rgb(245, 222, 179), 'white' => rgb(255, 255, 255), 'whitesmoke' => rgb(245, 245, 245), 'yellow' => rgb(255, 255, 0), 'yellowgreen' => rgb(154, 205, 50), }; } 1; =encoding utf8 =head1 NAME Graphics::ColorNames::WWW - WWW color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::WWW; $NameTable = Graphics::ColorNames::WWW->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from various WWW specifications, such as SVG or CSS. =head2 NOTE Reportedly "fuchsia" was misspelled "fuscia" in an unidentified HTML specification. It also appears to be a common misspelling, so both names are recognized. =head1 SEE ALSO C<Graphics::ColorNames>, SVG 1.2 Specificiation <http://www.w3.org/SVG/>, CSS Color Module Level 3 <http://www.w3.org/TR/css3-color>. =head1 AUTHOR Claus Färber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. =head1 LICENSE Copyright © 2005-2009 Claus Färber. Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
cfaerber/Graphics-ColorNames-WWW
3021d1428a88bea3261d1a6cdf7dba4d59e5d67a
new version 1.10: - added Graphics::ColorNames::CSS
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0409a5f --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +Makefile +Makefile.old +blib +Graphics-* +META.yml +SIGNATURE +pm_to_blib diff --git a/Changes b/Changes index f95c0af..79f689e 100644 --- a/Changes +++ b/Changes @@ -1,16 +1,17 @@ Revision history for Perl extension Graphics::ColorNames::WWW -1.10 Sat Sep 20 00:00:00 2008 +1.10 Fri Dec 11 00:00:00 2009 - added Graphics::ColorNames::CSS - re-organisation and cleanup - updated Makefile.PL - added LICENSE, SIGNATURE + - use Test::More and Test::NoWarnings + + - move to Github 1.00 Fri Sep 12 00:00:00 2008 - cleanup 0.01 Sat Nov 26 00:00:00 2005 - first public release - -$Id$ diff --git a/LICENSE b/LICENSE index 18a0dae..9d0305b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,381 +1,383 @@ Terms of Perl itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --------------------------------------------------------------------------- The General Public License (GPL) Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS --------------------------------------------------------------------------- The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End + + diff --git a/MANIFEST b/MANIFEST index 9701f23..f72b25b 100644 --- a/MANIFEST +++ b/MANIFEST @@ -1,13 +1,20 @@ -Makefile.PL +README +Changes +LICENSE MANIFEST -META.yml -WWW.pm -IE.pm -SVG.pm -t/00_WWW.t -t/10_SVG.t -t/11_IE.t -t/20_WWW_HTML.t -t/20_WWW_IE.t -t/20_WWW_Mozilla.t -t/20_WWW_SVG.t +Makefile.PL +lib/Graphics/ColorNames/CSS.pm +lib/Graphics/ColorNames/IE.pm +lib/Graphics/ColorNames/SVG.pm +lib/Graphics/ColorNames/WWW.pm +t/10pod.t +t/11pod_cover.t +t/CSS.t +t/IExplore.t +t/SVG.t +t/WWW.t +t/WWW_CSS.t +t/WWW_HTML.t +t/WWW_IExplore.t +t/WWW_Mozilla.t +t/WWW_SVG.t diff --git a/Makefile.PL b/Makefile.PL index b01d070..44dfc6e 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,13 +1,43 @@ use ExtUtils::MakeMaker; + # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'Graphics::ColorNames::WWW', - 'VERSION_FROM' => 'WWW.pm', # finds $VERSION + 'VERSION_FROM' => 'lib/Graphics/ColorNames/WWW.pm', 'PREREQ_PM' => { 'Graphics::ColorNames' => 0.32, }, - ($] >= 5.005 ? ## Add these new keywords supported since 5.005 - (ABSTRACT_FROM => 'WWW.pm', # retrieve abstract from module - AUTHOR => 'Claus Färber <CFAERBER@cpan.org>') : ()), + +$] < 5.005 ? () : ( + 'ABSTRACT_FROM' => 'lib/Graphics/ColorNames/WWW.pm', + 'AUTHOR' => 'Claus Faerber <CFAERBER@cpan.org>', + 'LICENSE' => 'perl', +), + +$ExtUtils::MakeMaker::VERSION < 6.18 ? () : ( + 'SIGN' => 1, +), + +$ExtUtils::MakeMaker::VERSION < 6.45 ? () : ( + 'META_MERGE' => { + 'build_requires' => { + 'Test::More' => 0, + 'Test::NoWarnings' => 0, + }, + 'resources' => { + 'homepage' => 'http://search.cpan.org/dist/Graphics-ColorNames-WWW', + 'repository' => 'http://github.com/cfaerber/Graphics-ColorNames-WWW', + }, + }, +), ); + +sub MY::postamble { +return <<EOF +release: release-cpan + +release-cpan: + cpan-upload \$(DISTVNAME).tar\$(SUFFIX) +EOF +} diff --git a/lib/Graphics/ColorNames/CSS.pm b/lib/Graphics/ColorNames/CSS.pm index 3f88319..d29e744 100644 --- a/lib/Graphics/ColorNames/CSS.pm +++ b/lib/Graphics/ColorNames/CSS.pm @@ -1,50 +1,48 @@ -# $Id$ -# package Graphics::ColorNames::CSS; require 5.006; use strict; use warnings; use Graphics::ColorNames::WWW(); our $VERSION = '1.10'; *NamesRgbTable = \&Graphics::ColorNames::WWW::NamesRgbTable; 1; =encoding utf8 =head1 NAME Graphics::ColorNames::CSS - CSS color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::CSS; $NameTable = Graphics::ColorNames::CSS->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from the CSS Color Module Level 3 Working Draft (2008-07-21). -It is actually an alias for L<Graphic::ColorNames::WWW>. +It is actually an alias for L<Graphic::ColorNames::WWW>. This may +change in the future should the specs happen to diverge. =head1 AUTHOR Claus Färber <CFAERBER@cpan.org> =head1 LICENSE -Copyright © 2005-2008 Claus Färber. +Copyright © 2005-2009 Claus Färber. All rights reserved. -All rights reserved. This program is free software; you can -redistribute it and/or modify it under the same terms as Perl -itself. +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. =cut diff --git a/lib/Graphics/ColorNames/IE.pm b/lib/Graphics/ColorNames/IE.pm index 0769ae2..a755323 100644 --- a/lib/Graphics/ColorNames/IE.pm +++ b/lib/Graphics/ColorNames/IE.pm @@ -1,202 +1,200 @@ -# $Id$ -# package Graphics::ColorNames::IE; require 5.006; use strict; use warnings; our $VERSION = '1.10'; sub NamesRgbTable() { use integer; return { (lc 'AliceBlue') => 0xF0F8FF, # 240,248,255 (lc 'AntiqueWhite') => 0xFAEBD7, # 250,235,215 (lc 'Aqua') => 0x00FFFF, # 0,255,255 (lc 'Aquamarine') => 0x7FFFD4, # 127,255,212 (lc 'Azure') => 0xF0FFFF, # 240,255,255 (lc 'Beige') => 0xF5F5DC, # 245,245,220 (lc 'Bisque') => 0xFFE4C4, # 255,228,196 (lc 'Black') => 0x000000, # 0,0,0 (lc 'BlanchedAlmond') => 0xFFEBCD, # 255,235,205 (lc 'Blue') => 0x0000FF, # 0,0,255 (lc 'BlueViolet') => 0x8A2BE2, # 138,43,226 (lc 'Brown') => 0xA52A2A, # 165,42,42 (lc 'BurlyWood') => 0xDEB887, # 222,184,135 (lc 'CadetBlue') => 0x5F9EA0, # 95,158,160 (lc 'Chartreuse') => 0x7FFF00, # 127,255,0 (lc 'Chocolate') => 0xD2691E, # 210,105,30 (lc 'Coral') => 0xFF7F50, # 255,127,80 (lc 'CornflowerBlue') => 0x6495ED, # 100,149,237 (lc 'Cornsilk') => 0xFFF8DC, # 255,248,220 (lc 'Crimson') => 0xDC143C, # 220,20,60 (lc 'Cyan') => 0x00FFFF, # 0,255,255 (lc 'DarkBlue') => 0x00008B, # 0,0,139 (lc 'DarkCyan') => 0x008B8B, # 0,139,139 (lc 'DarkGoldenrod') => 0xB8860B, # 184,134,11 (lc 'DarkGray') => 0xA9A9A9, # 169,169,169 (lc 'DarkGreen') => 0x006400, # 0,100,0 (lc 'DarkKhaki') => 0xBDB76B, # 189,183,107 (lc 'DarkMagenta') => 0x8B008B, # 139,0,139 (lc 'DarkOliveGreen') => 0x556B2F, # 85,107,47 (lc 'DarkOrange') => 0xFF8C00, # 255,140,0 (lc 'DarkOrchid') => 0x9932CC, # 153,50,204 (lc 'DarkRed') => 0x8B0000, # 139,0,0 (lc 'DarkSalmon') => 0xE9967A, # 233,150,122 (lc 'DarkSeaGreen') => 0x8FBC8F, # 143,188,143 (lc 'DarkSlateBlue') => 0x483D8B, # 72,61,139 (lc 'DarkSlateGray') => 0x2F4F4F, # 47,79,79 (lc 'DarkTurquoise') => 0x00CED1, # 0,206,209 (lc 'DarkViolet') => 0x9400D3, # 148,0,211 (lc 'DeepPink') => 0xFF1493, # 255,20,147 (lc 'DeepSkyBlue') => 0x00BFFF, # 0,191,255 (lc 'DimGray') => 0x696969, # 105,105,105 (lc 'DodgerBlue') => 0x1E90FF, # 30,144,255 (lc 'FireBrick') => 0xB22222, # 178,34,34 (lc 'FloralWhite') => 0xFFFAF0, # 255,250,240 (lc 'ForestGreen') => 0x228B22, # 34,139,34 (lc 'Fuchsia') => 0xFF00FF, # 255,0,255 (lc 'Gainsboro') => 0xDCDCDC, # 220,220,220 (lc 'GhostWhite') => 0xF8F8FF, # 248,248,255 (lc 'Gold') => 0xFFD700, # 255,215,0 (lc 'Goldenrod') => 0xDAA520, # 218,165,32 (lc 'Gray') => 0x808080, # 128,128,128 (lc 'Green') => 0x008000, # 0,128,0 (lc 'GreenYellow') => 0xADFF2F, # 173,255,47 (lc 'Honeydew') => 0xF0FFF0, # 240,255,240 (lc 'HotPink') => 0xFF69B4, # 255,105,180 (lc 'IndianRed') => 0xCD5C5C, # 205,92,92 (lc 'Indigo') => 0x4B0082, # 75,0,130 (lc 'Ivory') => 0xFFFFF0, # 255,255,240 (lc 'Khaki') => 0xF0E68C, # 240,230,140 (lc 'Lavender') => 0xE6E6FA, # 230,230,250 (lc 'LavenderBlush') => 0xFFF0F5, # 255,240,245 (lc 'LawnGreen') => 0x7CFC00, # 124,252,0 (lc 'LemonChiffon') => 0xFFFACD, # 255,250,205 (lc 'LightBlue') => 0xADD8E6, # 173,216,230 (lc 'LightCoral') => 0xF08080, # 240,128,128 (lc 'LightCyan') => 0xE0FFFF, # 224,255,255 (lc 'LightGoldenrodYellow') => 0xFAFAD2, # 250,250,210 (lc 'LightGreen') => 0x90EE90, # 144,238,144 (lc 'LightGrey') => 0xD3D3D3, # 211,211,211 (lc 'LightPink') => 0xFFB6C1, # 255,182,193 (lc 'LightSalmon') => 0xFFA07A, # 255,160,122 (lc 'LightSeaGreen') => 0x20B2AA, # 32,178,170 (lc 'LightSkyBlue') => 0x87CEFA, # 135,206,250 (lc 'LightSlateGray') => 0x778899, # 119,136,153 (lc 'LightSteelBlue') => 0xB0C4DE, # 176,196,222 (lc 'LightYellow') => 0xFFFFE0, # 255,255,224 (lc 'Lime') => 0x00FF00, # 0,255,0 (lc 'LimeGreen') => 0x32CD32, # 50,205,50 (lc 'Linen') => 0xFAF0E6, # 250,240,230 (lc 'Magenta') => 0xFF00FF, # 255,0,255 (lc 'Maroon') => 0x800000, # 128,0,0 (lc 'MediumAquamarine') => 0x66CDAA, # 102,205,170 (lc 'MediumBlue') => 0x0000CD, # 0,0,205 (lc 'MediumOrchid') => 0xBA55D3, # 186,85,211 (lc 'MediumPurple') => 0x9370DB, # 147,112,219 (lc 'MediumSeaGreen') => 0x3CB371, # 60,179,113 (lc 'MediumSlateBlue') => 0x7B68EE, # 123,104,238 (lc 'MediumSpringGreen') => 0x00FA9A, # 0,250,154 (lc 'MediumTurquoise') => 0x48D1CC, # 72,209,204 (lc 'MediumVioletRed') => 0xC71585, # 199,21,133 (lc 'MidnightBlue') => 0x191970, # 25,25,112 (lc 'MintCream') => 0xF5FFFA, # 245,255,250 (lc 'MistyRose') => 0xFFE4E1, # 255,228,225 (lc 'Moccasin') => 0xFFE4B5, # 255,228,181 (lc 'NavajoWhite') => 0xFFDEAD, # 255,222,173 (lc 'Navy') => 0x000080, # 0,0,128 (lc 'OldLace') => 0xFDF5E6, # 253,245,230 (lc 'Olive') => 0x808000, # 128,128,0 (lc 'OliveDrab') => 0x6B8E23, # 107,142,35 (lc 'Orange') => 0xFFA500, # 255,165,0 (lc 'OrangeRed') => 0xFF4500, # 255,69,0 (lc 'Orchid') => 0xDA70D6, # 218,112,214 (lc 'PaleGoldenrod') => 0xEEE8AA, # 238,232,170 (lc 'PaleGreen') => 0x98FB98, # 152,251,152 (lc 'PaleTurquoise') => 0xAFEEEE, # 175,238,238 (lc 'PaleVioletRed') => 0xDB7093, # 219,112,147 (lc 'PapayaWhip') => 0xFFEFD5, # 255,239,213 (lc 'PeachPuff') => 0xFFDAB9, # 255,218,185 (lc 'Peru') => 0xCD853F, # 205,133,63 (lc 'Pink') => 0xFFC0CB, # 255,192,203 (lc 'Plum') => 0xDDA0DD, # 221,160,221 (lc 'PowderBlue') => 0xB0E0E6, # 176,224,230 (lc 'Purple') => 0x800080, # 128,0,128 (lc 'Red') => 0xFF0000, # 255,0,0 (lc 'RosyBrown') => 0xBC8F8F, # 188,143,143 (lc 'RoyalBlue') => 0x4169E1, # 65,105,225 (lc 'SaddleBrown') => 0x8B4513, # 139,69,19 (lc 'Salmon') => 0xFA8072, # 250,128,114 (lc 'SandyBrown') => 0xF4A460, # 244,164,96 (lc 'SeaGreen') => 0x2E8B57, # 46,139,87 (lc 'Seashell') => 0xFFF5EE, # 255,245,238 (lc 'Sienna') => 0xA0522D, # 160,82,45 (lc 'Silver') => 0xC0C0C0, # 192,192,192 (lc 'SkyBlue') => 0x87CEEB, # 135,206,235 (lc 'SlateBlue') => 0x6A5ACD, # 106,90,205 (lc 'SlateGray') => 0x708090, # 112,128,144 (lc 'Snow') => 0xFFFAFA, # 255,250,250 (lc 'SpringGreen') => 0x00FF7F, # 0,255,127 (lc 'SteelBlue') => 0x4682B4, # 70,130,180 (lc 'Tan') => 0xD2B48C, # 210,180,140 (lc 'Teal') => 0x008080, # 0,128,128 (lc 'Thistle') => 0xD8BFD8, # 216,191,216 (lc 'Tomato') => 0xFF6347, # 255,99,71 (lc 'Turquoise') => 0x40E0D0, # 64,224,208 (lc 'Violet') => 0xEE82EE, # 238,130,238 (lc 'Wheat') => 0xF5DEB3, # 245,222,179 (lc 'White') => 0xFFFFFF, # 255,255,255 (lc 'WhiteSmoke') => 0xF5F5F5, # 245,245,245 (lc 'Yellow') => 0xFFFF00, # 255,255,0 (lc 'YellowGreen') => 0x9ACD32, # 154,205,50 }; } 1; =encoding utf8 =head1 NAME Graphics::ColorNames::IE - MS Internet Explorer color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::IE; $NameTable = Graphics::ColorNames::IE->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values recognized by Microsoft Internet Explorer. =head2 NOTE Although Microsoft calls them "X11 color names", some of them are not identical to the definitions in the X Specification. =head1 SEE ALSO C<Graphics::ColorNames>, MSDN <http://msdn.microsoft.com/library/en-us/dnwebgen/html/X11_names.asp> =head1 AUTHOR Claus Färber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. =head1 LICENSE -Copyright © 2005-2008 Claus Färber. +Copyright © 2005-2009 Claus Färber. Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Graphics/ColorNames/SVG.pm b/lib/Graphics/ColorNames/SVG.pm index 69d1b08..30a3334 100644 --- a/lib/Graphics/ColorNames/SVG.pm +++ b/lib/Graphics/ColorNames/SVG.pm @@ -1,50 +1,49 @@ -# $Id$ -# package Graphics::ColorNames::SVG; require 5.006; use strict; use warnings; use Graphics::ColorNames::WWW(); our $VERSION = '1.10'; *NamesRgbTable = \&Graphics::ColorNames::WWW::NamesRgbTable; 1; =encoding utf8 =head1 NAME Graphics::ColorNames::SVG - SVG color names and equivalent RGB values =head1 SYNOPSIS require Graphics::ColorNames::SVG; $NameTable = Graphics::ColorNames::SVG->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from the SVG 1.2 Specification. -It is actually an alias for L<Graphic::ColorNames::WWW>. +It is actually an alias for L<Graphic::ColorNames::WWW>. This may +change should the specs happen to diverge. =head1 AUTHOR Claus Färber <CFAERBER@cpan.org> =head1 LICENSE -Copyright © 2008 Claus Färber. +Copyright © 2008-2009 Claus Färber. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/lib/Graphics/ColorNames/WWW.pm b/lib/Graphics/ColorNames/WWW.pm index 1fffc9b..bd6e766 100644 --- a/lib/Graphics/ColorNames/WWW.pm +++ b/lib/Graphics/ColorNames/WWW.pm @@ -1,216 +1,214 @@ -# $Id$ -# -package Graphics::ColorNames::SVG; +package Graphics::ColorNames::WWW; require 5.006; use strict; use warnings; our $VERSION = '1.10'; sub NamesRgbTable() { sub rgb { ($_[0] << 16) + ($_[1] << 8) + ($_[2]) } use integer; return { 'aliceblue' => rgb(240, 248, 255), 'antiquewhite' => rgb(250, 235, 215), 'aqua' => rgb( 0, 255, 255), 'aquamarine' => rgb(127, 255, 212), 'azure' => rgb(240, 255, 255), 'beige' => rgb(245, 245, 220), 'bisque' => rgb(255, 228, 196), 'black' => rgb( 0, 0, 0), 'blanchedalmond' => rgb(255, 235, 205), 'blue' => rgb( 0, 0, 255), 'blueviolet' => rgb(138, 43, 226), 'brown' => rgb(165, 42, 42), 'burlywood' => rgb(222, 184, 135), 'cadetblue' => rgb( 95, 158, 160), 'chartreuse' => rgb(127, 255, 0), 'chocolate' => rgb(210, 105, 30), 'coral' => rgb(255, 127, 80), 'cornflowerblue' => rgb(100, 149, 237), 'cornsilk' => rgb(255, 248, 220), 'crimson' => rgb(220, 20, 60), 'cyan' => rgb( 0, 255, 255), 'darkblue' => rgb( 0, 0, 139), 'darkcyan' => rgb( 0, 139, 139), 'darkgoldenrod' => rgb(184, 134, 11), 'darkgray' => rgb(169, 169, 169), 'darkgreen' => rgb( 0, 100, 0), 'darkgrey' => rgb(169, 169, 169), 'darkkhaki' => rgb(189, 183, 107), 'darkmagenta' => rgb(139, 0, 139), 'darkolivegreen' => rgb( 85, 107, 47), 'darkorange' => rgb(255, 140, 0), 'darkorchid' => rgb(153, 50, 204), 'darkred' => rgb(139, 0, 0), 'darksalmon' => rgb(233, 150, 122), 'darkseagreen' => rgb(143, 188, 143), 'darkslateblue' => rgb( 72, 61, 139), 'darkslategray' => rgb( 47, 79, 79), 'darkslategrey' => rgb( 47, 79, 79), 'darkturquoise' => rgb( 0, 206, 209), 'darkviolet' => rgb(148, 0, 211), 'deeppink' => rgb(255, 20, 147), 'deepskyblue' => rgb( 0, 191, 255), 'dimgray' => rgb(105, 105, 105), 'dimgrey' => rgb(105, 105, 105), 'dodgerblue' => rgb( 30, 144, 255), 'firebrick' => rgb(178, 34, 34), 'floralwhite' => rgb(255, 250, 240), 'forestgreen' => rgb( 34, 139, 34), 'fuchsia' => 0xff00ff, # "fuscia" is incorrect but common 'fuscia' => 0xff00ff, # mis-spelling... 'gainsboro' => rgb(220, 220, 220), 'ghostwhite' => rgb(248, 248, 255), 'gold' => rgb(255, 215, 0), 'goldenrod' => rgb(218, 165, 32), 'gray' => rgb(128, 128, 128), 'grey' => rgb(128, 128, 128), 'green' => rgb( 0, 128, 0), 'greenyellow' => rgb(173, 255, 47), 'honeydew' => rgb(240, 255, 240), 'hotpink' => rgb(255, 105, 180), 'indianred' => rgb(205, 92, 92), 'indigo' => rgb( 75, 0, 130), 'ivory' => rgb(255, 255, 240), 'khaki' => rgb(240, 230, 140), 'lavender' => rgb(230, 230, 250), 'lavenderblush' => rgb(255, 240, 245), 'lawngreen' => rgb(124, 252, 0), 'lemonchiffon' => rgb(255, 250, 205), 'lightblue' => rgb(173, 216, 230), 'lightcoral' => rgb(240, 128, 128), 'lightcyan' => rgb(224, 255, 255), 'lightgoldenrodyellow' => rgb(250, 250, 210), 'lightgray' => rgb(211, 211, 211), 'lightgreen' => rgb(144, 238, 144), 'lightgrey' => rgb(211, 211, 211), 'lightpink' => rgb(255, 182, 193), 'lightsalmon' => rgb(255, 160, 122), 'lightseagreen' => rgb( 32, 178, 170), 'lightskyblue' => rgb(135, 206, 250), 'lightslategray' => rgb(119, 136, 153), 'lightslategrey' => rgb(119, 136, 153), 'lightsteelblue' => rgb(176, 196, 222), 'lightyellow' => rgb(255, 255, 224), 'lime' => rgb( 0, 255, 0), 'limegreen' => rgb( 50, 205, 50), 'linen' => rgb(250, 240, 230), 'magenta' => rgb(255, 0, 255), 'maroon' => rgb(128, 0, 0), 'mediumaquamarine' => rgb(102, 205, 170), 'mediumblue' => rgb( 0, 0, 205), 'mediumorchid' => rgb(186, 85, 211), 'mediumpurple' => rgb(147, 112, 219), 'mediumseagreen' => rgb( 60, 179, 113), 'mediumslateblue' => rgb(123, 104, 238), 'mediumspringgreen' => rgb( 0, 250, 154), 'mediumturquoise' => rgb( 72, 209, 204), 'mediumvioletred' => rgb(199, 21, 133), 'midnightblue' => rgb( 25, 25, 112), 'mintcream' => rgb(245, 255, 250), 'mistyrose' => rgb(255, 228, 225), 'moccasin' => rgb(255, 228, 181), 'navajowhite' => rgb(255, 222, 173), 'navy' => rgb( 0, 0, 128), 'oldlace' => rgb(253, 245, 230), 'olive' => rgb(128, 128, 0), 'olivedrab' => rgb(107, 142, 35), 'orange' => rgb(255, 165, 0), 'orangered' => rgb(255, 69, 0), 'orchid' => rgb(218, 112, 214), 'palegoldenrod' => rgb(238, 232, 170), 'palegreen' => rgb(152, 251, 152), 'paleturquoise' => rgb(175, 238, 238), 'palevioletred' => rgb(219, 112, 147), 'papayawhip' => rgb(255, 239, 213), 'peachpuff' => rgb(255, 218, 185), 'peru' => rgb(205, 133, 63), 'pink' => rgb(255, 192, 203), 'plum' => rgb(221, 160, 221), 'powderblue' => rgb(176, 224, 230), 'purple' => rgb(128, 0, 128), 'red' => rgb(255, 0, 0), 'rosybrown' => rgb(188, 143, 143), 'royalblue' => rgb( 65, 105, 225), 'saddlebrown' => rgb(139, 69, 19), 'salmon' => rgb(250, 128, 114), 'sandybrown' => rgb(244, 164, 96), 'seagreen' => rgb( 46, 139, 87), 'seashell' => rgb(255, 245, 238), 'sienna' => rgb(160, 82, 45), 'silver' => rgb(192, 192, 192), 'skyblue' => rgb(135, 206, 235), 'slateblue' => rgb(106, 90, 205), 'slategray' => rgb(112, 128, 144), 'slategrey' => rgb(112, 128, 144), 'snow' => rgb(255, 250, 250), 'springgreen' => rgb( 0, 255, 127), 'steelblue' => rgb( 70, 130, 180), 'tan' => rgb(210, 180, 140), 'teal' => rgb( 0, 128, 128), 'thistle' => rgb(216, 191, 216), 'tomato' => rgb(255, 99, 71), 'turquoise' => rgb( 64, 224, 208), 'violet' => rgb(238, 130, 238), 'wheat' => rgb(245, 222, 179), 'white' => rgb(255, 255, 255), 'whitesmoke' => rgb(245, 245, 245), 'yellow' => rgb(255, 255, 0), 'yellowgreen' => rgb(154, 205, 50), }; } 1; =encoding utf8 =head1 NAME -Graphics::ColorNames::SVG - SVG color names and equivalent RGB values +Graphics::ColorNames::WWW - WWW color names and equivalent RGB values =head1 SYNOPSIS - require Graphics::ColorNames::SVG; + require Graphics::ColorNames::WWW; - $NameTable = Graphics::ColorNames::SVG->NamesRgbTable(); + $NameTable = Graphics::ColorNames::WWW->NamesRgbTable(); $RgbBlack = $NameTable->{black}; =head1 DESCRIPTION This module defines color names and their associated RGB values from various WWW specifications, such as SVG or CSS. -=head2 Note +=head2 NOTE Reportedly "fuchsia" was misspelled "fuscia" in an unidentified HTML specification. It also appears to be a common misspelling, so both names are recognized. =head1 SEE ALSO C<Graphics::ColorNames>, SVG 1.2 Specificiation <http://www.w3.org/SVG/>, CSS Color Module Level 3 <http://www.w3.org/TR/css3-color>. =head1 AUTHOR Claus Färber <CFAERBER@cpan.org> Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. =head1 LICENSE -Copyright © 2005-2008 Claus Färber. +Copyright © 2005-2009 Claus Färber. Copyright © 2001-2004 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut diff --git a/t/10pod.t b/t/10pod.t index c3073fe..0f75ddc 100644 --- a/t/10pod.t +++ b/t/10pod.t @@ -1,9 +1,7 @@ -# $Id$ - use strict; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); diff --git a/t/11pod_cover.t b/t/11pod_cover.t index f10ca82..8e593aa 100644 --- a/t/11pod_cover.t +++ b/t/11pod_cover.t @@ -1,15 +1,13 @@ -# $Id$ - use strict; use Test::More; eval "use Test::Pod::Coverage;"; plan skip_all => "Test::Pod::Coverage required for testing POD coverage" if $@; plan tests => 2; pod_coverage_ok( 'Color::Calc', { trustme => [ qr/_(tuple|html|pdf|hex|obj|object)$/, qr/^color(_.+)?$/ ], }, 'Color::Calc is covered by POD' ); pod_coverage_ok( 'Color::Calc::WWW', 'Color::Calc::WWW is covered by POD' ); diff --git a/t/CSS.t b/t/CSS.t index 0d4afa8..bcdb0f4 100644 --- a/t/CSS.t +++ b/t/CSS.t @@ -1,18 +1,15 @@ -use Test; - -BEGIN { - plan tests => 5, todo => [ ] -} +use Test::More tests => 6; +use Test::NoWarnings; use strict; use Carp; use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); ok(1); tie my %colors, 'Graphics::ColorNames', 'CSS'; ok(1); ok(exists($colors{"fuchsia"})); ok(exists($colors{"fuscia"})); ok($colors{"fuscia"} eq $colors{"fuchsia"}); diff --git a/t/IExplore.t b/t/IExplore.t index e4e893a..abce50e 100644 --- a/t/IExplore.t +++ b/t/IExplore.t @@ -1,29 +1,24 @@ -use Test; - - -BEGIN { - my $colors = 140; - plan tests => 6 + $colors, todo => [ ] -} +use Test::More tests => 140 + 7; +use Test::NoWarnings; use strict; use Carp; use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); ok(1); tie my %colors, 'Graphics::ColorNames', 'IE'; ok(1); -ok(keys %colors, 140); +is(keys %colors, 140); my $count = 0; foreach my $name (keys %colors) { my @RGB = hex2tuple( $colors{$name} ); - ok(tuple2hex(@RGB), $colors{$name} ); + is(tuple2hex(@RGB), $colors{$name} ); } -ok(uc $colors{'white'}, 'FFFFFF'); -ok(uc $colors{'blue'}, '0000FF'); -ok(uc $colors{'cyan'}, '00FFFF'); +is(uc $colors{'white'}, 'FFFFFF'); +is(uc $colors{'blue'}, '0000FF'); +is(uc $colors{'cyan'}, '00FFFF'); diff --git a/t/SVG.t b/t/SVG.t index 4bc8d2d..6e90db6 100644 --- a/t/SVG.t +++ b/t/SVG.t @@ -1,33 +1,28 @@ -use Test; - - -BEGIN { - my $colors = 148; - plan tests => 9 + $colors, todo => [ ] -} +use Test::More tests => 10 + 148; +use Test::NoWarnings; use strict; use Carp; use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); ok(1); tie my %colors, 'Graphics::ColorNames', 'SVG'; ok(1); -ok(keys %colors, 148); +is(keys %colors, 148); my $count = 0; foreach my $name (keys %colors) { my @RGB = hex2tuple( $colors{$name} ); - ok(tuple2hex(@RGB), $colors{$name} ); + is(tuple2hex(@RGB), $colors{$name} ); } ok(exists($colors{"fuchsia"})); ok(exists($colors{"fuscia"})); ok($colors{"fuscia"} eq $colors{"fuchsia"}); -ok(uc $colors{'white'}, 'FFFFFF'); -ok(uc $colors{'blue'}, '0000FF'); -ok(uc $colors{'cyan'}, '00FFFF'); +is(uc $colors{'white'}, 'FFFFFF'); +is(uc $colors{'blue'}, '0000FF'); +is(uc $colors{'cyan'}, '00FFFF'); diff --git a/t/WWW.t b/t/WWW.t index 2fe8a22..b5ad6ba 100644 --- a/t/WWW.t +++ b/t/WWW.t @@ -1,18 +1,15 @@ -use Test; - -BEGIN { - plan tests => 5, todo => [ ] -} +use Test::More tests => 6; +use Test::NoWarnings; use strict; use Carp; use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); ok(1); tie my %colors, 'Graphics::ColorNames', 'WWW'; ok(1); ok(exists($colors{"fuchsia"})); ok(exists($colors{"fuscia"})); ok($colors{"fuscia"} eq $colors{"fuchsia"}); diff --git a/t/WWW_CSS.t b/t/WWW_CSS.t index a6be0ff..2a8f1c5 100644 --- a/t/WWW_CSS.t +++ b/t/WWW_CSS.t @@ -1,21 +1,16 @@ -use Test; - - -BEGIN { - my $colors = 148; - plan tests => $colors, todo => [ ] -} +use Test::More tests => 148 + 1; +use Test::NoWarnings; use strict; use Carp; use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); tie my %col_www, 'Graphics::ColorNames', 'WWW'; tie my %colors, 'Graphics::ColorNames', 'CSS'; my $count = 0; foreach my $name (keys %colors) { my @RGB = hex2tuple( $colors{$name} ); - ok(tuple2hex(@RGB), $col_www{$name} ); + is(tuple2hex(@RGB), $col_www{$name} ); } diff --git a/t/WWW_HTML.t b/t/WWW_HTML.t index f00eb5b..4191c53 100644 --- a/t/WWW_HTML.t +++ b/t/WWW_HTML.t @@ -1,21 +1,16 @@ -use Test; - - -BEGIN { - my $colors = 17; - plan tests => $colors, todo => [ ] -} +use Test::More tests => 17 + 1; +use Test::NoWarnings; use strict; use Carp; use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); tie my %colors, 'Graphics::ColorNames', 'HTML'; tie my %col_www, 'Graphics::ColorNames', 'WWW'; my $count = 0; foreach my $name (keys %colors) { my @RGB = hex2tuple( $colors{$name} ); - ok($name.'-'.tuple2hex(@RGB), $name.'-'.$col_www{$name} ); + is($name.'-'.tuple2hex(@RGB), $name.'-'.$col_www{$name} ); } diff --git a/t/WWW_IExplore.t b/t/WWW_IExplore.t index 05643c4..5623df2 100644 --- a/t/WWW_IExplore.t +++ b/t/WWW_IExplore.t @@ -1,21 +1,16 @@ -use Test; - - -BEGIN { - my $colors = 193-53; - plan tests => $colors, todo => [ ] -} +use Test::More tests => 193 - 53 + 1; +use Test::NoWarnings; use strict; use Carp; use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); tie my %col_www, 'Graphics::ColorNames', 'WWW'; tie my %colors, 'Graphics::ColorNames', 'IE'; my $count = 0; foreach my $name (keys %colors) { my @RGB = hex2tuple( $colors{$name} ); - ok(tuple2hex(@RGB), $col_www{$name} ); + is(tuple2hex(@RGB), $col_www{$name} ); } diff --git a/t/WWW_Mozilla.t b/t/WWW_Mozilla.t index 6aea990..7e78136 100644 --- a/t/WWW_Mozilla.t +++ b/t/WWW_Mozilla.t @@ -1,19 +1,20 @@ -use Test::More tests => 146; +use Test::More tests => 147; +use Test::NoWarnings; use strict; use Carp; SKIP: { eval { require Graphics::ColorNames::Mozilla; }; skip ("Graphics::ColorNames::Mozilla not installed", 146) if $@; use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); tie my %col_www, 'Graphics::ColorNames', 'WWW'; tie my %colors, 'Graphics::ColorNames', 'Mozilla'; foreach my $name (keys %colors) { my @RGB = hex2tuple( $colors{$name} ); is(tuple2hex(@RGB), $col_www{$name} ); } } diff --git a/t/WWW_SVG.t b/t/WWW_SVG.t index b74a509..f2df068 100644 --- a/t/WWW_SVG.t +++ b/t/WWW_SVG.t @@ -1,21 +1,16 @@ -use Test; - - -BEGIN { - my $colors = 148; - plan tests => $colors, todo => [ ] -} +use Test::More tests => 148 + 1; +use Test::NoWarnings; use strict; use Carp; use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); tie my %col_www, 'Graphics::ColorNames', 'WWW'; tie my %colors, 'Graphics::ColorNames', 'SVG'; my $count = 0; foreach my $name (keys %colors) { my @RGB = hex2tuple( $colors{$name} ); - ok(tuple2hex(@RGB), $col_www{$name} ); + is(tuple2hex(@RGB), $col_www{$name} ); }
cfaerber/Graphics-ColorNames-WWW
10994c78c1cb50fd8ee2209d16cb3b9686fe67d2
prepare to split Graphics-Color-Names-WWW
diff --git a/Changes b/Changes new file mode 100644 index 0000000..f95c0af --- /dev/null +++ b/Changes @@ -0,0 +1,16 @@ +Revision history for Perl extension Graphics::ColorNames::WWW + +1.10 Sat Sep 20 00:00:00 2008 + - added Graphics::ColorNames::CSS + + - re-organisation and cleanup + - updated Makefile.PL + - added LICENSE, SIGNATURE + +1.00 Fri Sep 12 00:00:00 2008 + - cleanup + +0.01 Sat Nov 26 00:00:00 2005 + - first public release + +$Id$ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..18a0dae --- /dev/null +++ b/LICENSE @@ -0,0 +1,381 @@ +Terms of Perl itself + +a) the GNU General Public License as published by the Free + Software Foundation; either version 1, or (at your option) any + later version, or +b) the "Artistic License" + +--------------------------------------------------------------------------- + +The General Public License (GPL) +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, +Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute +verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share +and change it. By contrast, the GNU General Public License is intended to +guarantee your freedom to share and change free software--to make sure the +software is free for all its users. This General Public License applies to most of +the Free Software Foundation's software and to any other program whose +authors commit to using it. (Some other Free Software Foundation software is +covered by the GNU Library General Public License instead.) You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom +to distribute copies of free software (and charge for this service if you wish), that +you receive source code or can get it if you want it, that you can change the +software or use pieces of it in new free programs; and that you know you can do +these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny +you these rights or to ask you to surrender the rights. These restrictions +translate to certain responsibilities for you if you distribute copies of the +software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a +fee, you must give the recipients all the rights that you have. You must make +sure that they, too, receive or can get the source code. And you must show +them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer +you this license which gives you legal permission to copy, distribute and/or +modify the software. + +Also, for each author's protection and ours, we want to make certain that +everyone understands that there is no warranty for this free software. If the +software is modified by someone else and passed on, we want its recipients to +know that what they have is not the original, so that any problems introduced by +others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish +to avoid the danger that redistributors of a free program will individually obtain +patent licenses, in effect making the program proprietary. To prevent this, we +have made it clear that any patent must be licensed for everyone's free use or +not licensed at all. + +The precise terms and conditions for copying, distribution and modification +follow. + +GNU GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND +MODIFICATION + +0. This License applies to any program or other work which contains a notice +placed by the copyright holder saying it may be distributed under the terms of +this General Public License. The "Program", below, refers to any such program +or work, and a "work based on the Program" means either the Program or any +derivative work under copyright law: that is to say, a work containing the +Program or a portion of it, either verbatim or with modifications and/or translated +into another language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by +this License; they are outside its scope. The act of running the Program is not +restricted, and the output from the Program is covered only if its contents +constitute a work based on the Program (independent of having been made by +running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as +you receive it, in any medium, provided that you conspicuously and appropriately +publish on each copy an appropriate copyright notice and disclaimer of warranty; +keep intact all the notices that refer to this License and to the absence of any +warranty; and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at +your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus +forming a work based on the Program, and copy and distribute such +modifications or work under the terms of Section 1 above, provided that you also +meet all of these conditions: + +a) You must cause the modified files to carry prominent notices stating that you +changed the files and the date of any change. + +b) You must cause any work that you distribute or publish, that in whole or in +part contains or is derived from the Program or any part thereof, to be licensed +as a whole at no charge to all third parties under the terms of this License. + +c) If the modified program normally reads commands interactively when run, you +must cause it, when started running for such interactive use in the most ordinary +way, to print or display an announcement including an appropriate copyright +notice and a notice that there is no warranty (or else, saying that you provide a +warranty) and that users may redistribute the program under these conditions, +and telling the user how to view a copy of this License. (Exception: if the +Program itself is interactive but does not normally print such an announcement, +your work based on the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable +sections of that work are not derived from the Program, and can be reasonably +considered independent and separate works in themselves, then this License, +and its terms, do not apply to those sections when you distribute them as +separate works. But when you distribute the same sections as part of a whole +which is a work based on the Program, the distribution of the whole must be on +the terms of this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to +work written entirely by you; rather, the intent is to exercise the right to control +the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the +Program (or with a work based on the Program) on a volume of a storage or +distribution medium does not bring the other work under the scope of this +License. + +3. You may copy and distribute the Program (or a work based on it, under +Section 2) in object code or executable form under the terms of Sections 1 and 2 +above provided that you also do one of the following: + +a) Accompany it with the complete corresponding machine-readable source +code, which must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange; or, + +b) Accompany it with a written offer, valid for at least three years, to give any +third party, for a charge no more than your cost of physically performing source +distribution, a complete machine-readable copy of the corresponding source +code, to be distributed under the terms of Sections 1 and 2 above on a medium +customarily used for software interchange; or, + +c) Accompany it with the information you received as to the offer to distribute +corresponding source code. (This alternative is allowed only for noncommercial +distribution and only if you received the program in object code or executable +form with such an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for making +modifications to it. For an executable work, complete source code means all the +source code for all modules it contains, plus any associated interface definition +files, plus the scripts used to control compilation and installation of the +executable. However, as a special exception, the source code distributed need +not include anything that is normally distributed (in either source or binary form) +with the major components (compiler, kernel, and so on) of the operating system +on which the executable runs, unless that component itself accompanies the +executable. + +If distribution of executable or object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the source +code from the same place counts as distribution of the source code, even though +third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as +expressly provided under this License. Any attempt otherwise to copy, modify, +sublicense or distribute the Program is void, and will automatically terminate +your rights under this License. However, parties who have received copies, or +rights, from you under this License will not have their licenses terminated so long +as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. +However, nothing else grants you permission to modify or distribute the Program +or its derivative works. These actions are prohibited by law if you do not accept +this License. Therefore, by modifying or distributing the Program (or any work +based on the Program), you indicate your acceptance of this License to do so, +and all its terms and conditions for copying, distributing or modifying the +Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), +the recipient automatically receives a license from the original licensor to copy, +distribute or modify the Program subject to these terms and conditions. You +may not impose any further restrictions on the recipients' exercise of the rights +granted herein. You are not responsible for enforcing compliance by third parties +to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement +or for any other reason (not limited to patent issues), conditions are imposed on +you (whether by court order, agreement or otherwise) that contradict the +conditions of this License, they do not excuse you from the conditions of this +License. If you cannot distribute so as to satisfy simultaneously your obligations +under this License and any other pertinent obligations, then as a consequence +you may not distribute the Program at all. For example, if a patent license would +not permit royalty-free redistribution of the Program by all those who receive +copies directly or indirectly through you, then the only way you could satisfy +both it and this License would be to refrain entirely from distribution of the +Program. + +If any portion of this section is held invalid or unenforceable under any particular +circumstance, the balance of the section is intended to apply and the section as +a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other +property right claims or to contest validity of any such claims; this section has +the sole purpose of protecting the integrity of the free software distribution +system, which is implemented by public license practices. Many people have +made generous contributions to the wide range of software distributed through +that system in reliance on consistent application of that system; it is up to the +author/donor to decide if he or she is willing to distribute software through any +other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a +consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries +either by patents or by copyrighted interfaces, the original copyright holder who +places the Program under this License may add an explicit geographical +distribution limitation excluding those countries, so that distribution is permitted +only in or among countries not thus excluded. In such case, this License +incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the +General Public License from time to time. Such new versions will be similar in +spirit to the present version, but may differ in detail to address new problems or +concerns. + +Each version is given a distinguishing version number. If the Program specifies a +version number of this License which applies to it and "any later version", you +have the option of following the terms and conditions either of that version or of +any later version published by the Free Software Foundation. If the Program does +not specify a version number of this License, you may choose any version ever +published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs +whose distribution conditions are different, write to the author to ask for +permission. For software which is copyrighted by the Free Software Foundation, +write to the Free Software Foundation; we sometimes make exceptions for this. +Our decision will be guided by the two goals of preserving the free status of all +derivatives of our free software and of promoting the sharing and reuse of +software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS +NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE +COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM +"AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR +IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE +ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, +YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED +TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY +WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS +PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM +(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY +OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + + +--------------------------------------------------------------------------- + +The Artistic License + +Preamble + +The intent of this document is to state the conditions under which a Package +may be copied, such that the Copyright Holder maintains some semblance of +artistic control over the development of the package, while giving the users of the +package the right to use and distribute the Package in a more-or-less customary +fashion, plus the right to make reasonable modifications. + +Definitions: + +- "Package" refers to the collection of files distributed by the Copyright + Holder, and derivatives of that collection of files created through textual + modification. +- "Standard Version" refers to such a Package if it has not been modified, + or has been modified in accordance with the wishes of the Copyright + Holder. +- "Copyright Holder" is whoever is named in the copyright or copyrights for + the package. +- "You" is you, if you're thinking about copying or distributing this Package. +- "Reasonable copying fee" is whatever you can justify on the basis of + media cost, duplication charges, time of people involved, and so on. (You + will not be required to justify it to the Copyright Holder, but only to the + computing community at large as a market that must bear the fee.) +- "Freely Available" means that no fee is charged for the item itself, though + there may be fees involved in handling the item. It also means that + recipients of the item may redistribute it under the same conditions they + received it. + +1. You may make and give away verbatim copies of the source form of the +Standard Version of this Package without restriction, provided that you duplicate +all of the original copyright notices and associated disclaimers. + +2. You may apply bug fixes, portability fixes and other modifications derived from +the Public Domain or from the Copyright Holder. A Package modified in such a +way shall still be considered the Standard Version. + +3. You may otherwise modify your copy of this Package in any way, provided +that you insert a prominent notice in each changed file stating how and when +you changed that file, and provided that you do at least ONE of the following: + + a) place your modifications in the Public Domain or otherwise + make them Freely Available, such as by posting said modifications + to Usenet or an equivalent medium, or placing the modifications on + a major archive site such as ftp.uu.net, or by allowing the + Copyright Holder to include your modifications in the Standard + Version of the Package. + + b) use the modified Package only within your corporation or + organization. + + c) rename any non-standard executables so the names do not + conflict with standard executables, which must also be provided, + and provide a separate manual page for each non-standard + executable that clearly documents how it differs from the Standard + Version. + + d) make other distribution arrangements with the Copyright Holder. + +4. You may distribute the programs of this Package in object code or executable +form, provided that you do at least ONE of the following: + + a) distribute a Standard Version of the executables and library + files, together with instructions (in the manual page or equivalent) + on where to get the Standard Version. + + b) accompany the distribution with the machine-readable source of + the Package with your modifications. + + c) accompany any non-standard executables with their + corresponding Standard Version executables, giving the + non-standard executables non-standard names, and clearly + documenting the differences in manual pages (or equivalent), + together with instructions on where to get the Standard Version. + + d) make other distribution arrangements with the Copyright Holder. + +5. You may charge a reasonable copying fee for any distribution of this Package. +You may charge any fee you choose for support of this Package. You may not +charge a fee for this Package itself. However, you may distribute this Package in +aggregate with other (possibly commercial) programs as part of a larger +(possibly commercial) software distribution provided that you do not advertise +this Package as a product of your own. + +6. The scripts and library files supplied as input to or produced as output from +the programs of this Package do not automatically fall under the copyright of this +Package, but belong to whomever generated them, and may be sold +commercially, and may be aggregated with this Package. + +7. C or perl subroutines supplied by you and linked into this Package shall not +be considered part of this Package. + +8. Aggregation of this Package with a commercial distribution is always permitted +provided that the use of this Package is embedded; that is, when no overt attempt +is made to make this Package's interfaces visible to the end user of the +commercial distribution. Such use shall not be construed as a distribution of +this Package. + +9. The name of the Copyright Holder may not be used to endorse or promote +products derived from this software without specific prior written permission. + +10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED +WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR +PURPOSE. + +The End diff --git a/README b/README new file mode 100644 index 0000000..0c69975 --- /dev/null +++ b/README @@ -0,0 +1,36 @@ +Graphics::ColorNames::WWW + + The "Graphics:ColorNames::WWW" module provides the full list of + color names from various Web specifications and implementations. + +INSTALLATION + + To install this module type the following: + + perl Makefile.PL + make + make test + make install + +DEPENDENCIES + + This module requires these other modules and libraries: + + - Graphics::ColorNames + +AUTHOR + + Claus Färber <CFAERBER@cpan.org> + + Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. + +LICENSE + + Copyright © 2005-2008 Claus Färber. + + Copyright © 2001-2004 Robert Rothenberg. + + All rights reserved. This program is free software; you can redistribute it + and/or modify it under the same terms as Perl itself. + +$Id$ diff --git a/WWW.pm b/WWW.pm deleted file mode 100644 index 62a5b5c..0000000 --- a/WWW.pm +++ /dev/null @@ -1,68 +0,0 @@ -package Graphics::ColorNames::WWW; - -=head1 NAME - -Graphics::ColorNames::WWW - WWW color names and equivalent RGB values - -=head1 SYNOPSIS - - require Graphics::ColorNames::WWW; - - $NameTable = Graphics::ColorNames::WWW->NamesRgbTable(); - $RgbBlack = $NameTable->{black}; - -=head1 DESCRIPTION - -This modules defines color names and their associated RGB values from various -WWW specifications and implementations. - -=cut - -# Note: Mozilla is a subset of SVG -# Note: HTML is a subset of HTML - -my @modules = ( - 'SVG', -# 'HTML', -- subset of SVG -# 'Mozilla', -- subset of SVG -# 'IE', -- subset of SVG -); - -=head1 SEE ALSO - -C<Graphics::ColorNames> - -=head1 AUTHOR - -Claus Färber <CFAERBER@cpan.org> - -=head1 LICENSE - -Copyright © 2005-2008 Claus Färber - -Based on C<Graphics::ColorNames::HTML> Copyright © 2001-2004 Robert Rothenberg. - -All rights reserved. This program is free software; you can redistribute it -and/or modify it under the same terms as Perl itself. - -=cut - -require 5.006; - -use strict; -use warnings; - -our $VERSION = '1.00'; - -sub NamesRgbTable() { - my %map = (); - foreach (@modules) { - eval "use Graphics::ColorNames::$_;"; die $@ if $@; - %map = ((%map),%{eval "Graphics::ColorNames::$_->NamesRgbTable"}); - } - return \%map; -} - -1; - -__END__ diff --git a/lib/Graphics/ColorNames/CSS.pm b/lib/Graphics/ColorNames/CSS.pm new file mode 100644 index 0000000..3f88319 --- /dev/null +++ b/lib/Graphics/ColorNames/CSS.pm @@ -0,0 +1,50 @@ +# $Id$ +# +package Graphics::ColorNames::CSS; + +require 5.006; + +use strict; +use warnings; + +use Graphics::ColorNames::WWW(); + +our $VERSION = '1.10'; + +*NamesRgbTable = \&Graphics::ColorNames::WWW::NamesRgbTable; + +1; + +=encoding utf8 + +=head1 NAME + +Graphics::ColorNames::CSS - CSS color names and equivalent RGB values + +=head1 SYNOPSIS + + require Graphics::ColorNames::CSS; + + $NameTable = Graphics::ColorNames::CSS->NamesRgbTable(); + $RgbBlack = $NameTable->{black}; + +=head1 DESCRIPTION + +This module defines color names and their associated RGB values +from the CSS Color Module Level 3 Working Draft (2008-07-21). + +It is actually an alias for L<Graphic::ColorNames::WWW>. + +=head1 AUTHOR + +Claus Färber <CFAERBER@cpan.org> + +=head1 LICENSE + +Copyright © 2005-2008 Claus Färber. + +All rights reserved. This program is free software; you can +redistribute it and/or modify it under the same terms as Perl +itself. + +=cut diff --git a/IE.pm b/lib/Graphics/ColorNames/IE.pm similarity index 97% rename from IE.pm rename to lib/Graphics/ColorNames/IE.pm index 16085d4..0769ae2 100644 --- a/IE.pm +++ b/lib/Graphics/ColorNames/IE.pm @@ -1,198 +1,202 @@ +# $Id$ +# package Graphics::ColorNames::IE; -=head1 NAME - -Graphics::ColorNames::IE - MS Internet Explorer color names and equivalent RGB values - -=head1 SYNOPSIS - - require Graphics::ColorNames::IE; - - $NameTable = Graphics::ColorNames::IE->NamesRgbTable(); - $RgbBlack = $NameTable->{black}; - -=head1 DESCRIPTION - -This module defines color names and their associated RGB values recognized by -Microsoft Internet Explorer. - -=head2 Note - -Although Microsoft calls them "X11 color names", some of them are not identical -to the definitions in the X Specification. - -=head1 SEE ALSO - -C<Graphics::ColorNames>, MSDN <http://msdn.microsoft.com/library/en-us/dnwebgen/html/X11_names.asp> - -=head1 AUTHOR - -Claus Färber <CFAERBER@cpan.org> - -=head1 LICENSE - -Copyright © 2005-2008 Claus Färber - -Based on C<Graphics::ColorNames::HTML> Copyright © 2001-2004 Robert Rothenberg. - -All rights reserved. This program is free software; you can redistribute it -and/or modify it under the same terms as Perl itself. - -=cut - require 5.006; use strict; use warnings; -our $VERSION = '1.00'; +our $VERSION = '1.10'; sub NamesRgbTable() { use integer; return { (lc 'AliceBlue') => 0xF0F8FF, # 240,248,255 (lc 'AntiqueWhite') => 0xFAEBD7, # 250,235,215 (lc 'Aqua') => 0x00FFFF, # 0,255,255 (lc 'Aquamarine') => 0x7FFFD4, # 127,255,212 (lc 'Azure') => 0xF0FFFF, # 240,255,255 (lc 'Beige') => 0xF5F5DC, # 245,245,220 (lc 'Bisque') => 0xFFE4C4, # 255,228,196 (lc 'Black') => 0x000000, # 0,0,0 (lc 'BlanchedAlmond') => 0xFFEBCD, # 255,235,205 (lc 'Blue') => 0x0000FF, # 0,0,255 (lc 'BlueViolet') => 0x8A2BE2, # 138,43,226 (lc 'Brown') => 0xA52A2A, # 165,42,42 (lc 'BurlyWood') => 0xDEB887, # 222,184,135 (lc 'CadetBlue') => 0x5F9EA0, # 95,158,160 (lc 'Chartreuse') => 0x7FFF00, # 127,255,0 (lc 'Chocolate') => 0xD2691E, # 210,105,30 (lc 'Coral') => 0xFF7F50, # 255,127,80 (lc 'CornflowerBlue') => 0x6495ED, # 100,149,237 (lc 'Cornsilk') => 0xFFF8DC, # 255,248,220 (lc 'Crimson') => 0xDC143C, # 220,20,60 (lc 'Cyan') => 0x00FFFF, # 0,255,255 (lc 'DarkBlue') => 0x00008B, # 0,0,139 (lc 'DarkCyan') => 0x008B8B, # 0,139,139 (lc 'DarkGoldenrod') => 0xB8860B, # 184,134,11 (lc 'DarkGray') => 0xA9A9A9, # 169,169,169 (lc 'DarkGreen') => 0x006400, # 0,100,0 (lc 'DarkKhaki') => 0xBDB76B, # 189,183,107 (lc 'DarkMagenta') => 0x8B008B, # 139,0,139 (lc 'DarkOliveGreen') => 0x556B2F, # 85,107,47 (lc 'DarkOrange') => 0xFF8C00, # 255,140,0 (lc 'DarkOrchid') => 0x9932CC, # 153,50,204 (lc 'DarkRed') => 0x8B0000, # 139,0,0 (lc 'DarkSalmon') => 0xE9967A, # 233,150,122 (lc 'DarkSeaGreen') => 0x8FBC8F, # 143,188,143 (lc 'DarkSlateBlue') => 0x483D8B, # 72,61,139 (lc 'DarkSlateGray') => 0x2F4F4F, # 47,79,79 (lc 'DarkTurquoise') => 0x00CED1, # 0,206,209 (lc 'DarkViolet') => 0x9400D3, # 148,0,211 (lc 'DeepPink') => 0xFF1493, # 255,20,147 (lc 'DeepSkyBlue') => 0x00BFFF, # 0,191,255 (lc 'DimGray') => 0x696969, # 105,105,105 (lc 'DodgerBlue') => 0x1E90FF, # 30,144,255 (lc 'FireBrick') => 0xB22222, # 178,34,34 (lc 'FloralWhite') => 0xFFFAF0, # 255,250,240 (lc 'ForestGreen') => 0x228B22, # 34,139,34 (lc 'Fuchsia') => 0xFF00FF, # 255,0,255 (lc 'Gainsboro') => 0xDCDCDC, # 220,220,220 (lc 'GhostWhite') => 0xF8F8FF, # 248,248,255 (lc 'Gold') => 0xFFD700, # 255,215,0 (lc 'Goldenrod') => 0xDAA520, # 218,165,32 (lc 'Gray') => 0x808080, # 128,128,128 (lc 'Green') => 0x008000, # 0,128,0 (lc 'GreenYellow') => 0xADFF2F, # 173,255,47 (lc 'Honeydew') => 0xF0FFF0, # 240,255,240 (lc 'HotPink') => 0xFF69B4, # 255,105,180 (lc 'IndianRed') => 0xCD5C5C, # 205,92,92 (lc 'Indigo') => 0x4B0082, # 75,0,130 (lc 'Ivory') => 0xFFFFF0, # 255,255,240 (lc 'Khaki') => 0xF0E68C, # 240,230,140 (lc 'Lavender') => 0xE6E6FA, # 230,230,250 (lc 'LavenderBlush') => 0xFFF0F5, # 255,240,245 (lc 'LawnGreen') => 0x7CFC00, # 124,252,0 (lc 'LemonChiffon') => 0xFFFACD, # 255,250,205 (lc 'LightBlue') => 0xADD8E6, # 173,216,230 (lc 'LightCoral') => 0xF08080, # 240,128,128 (lc 'LightCyan') => 0xE0FFFF, # 224,255,255 (lc 'LightGoldenrodYellow') => 0xFAFAD2, # 250,250,210 (lc 'LightGreen') => 0x90EE90, # 144,238,144 (lc 'LightGrey') => 0xD3D3D3, # 211,211,211 (lc 'LightPink') => 0xFFB6C1, # 255,182,193 (lc 'LightSalmon') => 0xFFA07A, # 255,160,122 (lc 'LightSeaGreen') => 0x20B2AA, # 32,178,170 (lc 'LightSkyBlue') => 0x87CEFA, # 135,206,250 (lc 'LightSlateGray') => 0x778899, # 119,136,153 (lc 'LightSteelBlue') => 0xB0C4DE, # 176,196,222 (lc 'LightYellow') => 0xFFFFE0, # 255,255,224 (lc 'Lime') => 0x00FF00, # 0,255,0 (lc 'LimeGreen') => 0x32CD32, # 50,205,50 (lc 'Linen') => 0xFAF0E6, # 250,240,230 (lc 'Magenta') => 0xFF00FF, # 255,0,255 (lc 'Maroon') => 0x800000, # 128,0,0 (lc 'MediumAquamarine') => 0x66CDAA, # 102,205,170 (lc 'MediumBlue') => 0x0000CD, # 0,0,205 (lc 'MediumOrchid') => 0xBA55D3, # 186,85,211 (lc 'MediumPurple') => 0x9370DB, # 147,112,219 (lc 'MediumSeaGreen') => 0x3CB371, # 60,179,113 (lc 'MediumSlateBlue') => 0x7B68EE, # 123,104,238 (lc 'MediumSpringGreen') => 0x00FA9A, # 0,250,154 (lc 'MediumTurquoise') => 0x48D1CC, # 72,209,204 (lc 'MediumVioletRed') => 0xC71585, # 199,21,133 (lc 'MidnightBlue') => 0x191970, # 25,25,112 (lc 'MintCream') => 0xF5FFFA, # 245,255,250 (lc 'MistyRose') => 0xFFE4E1, # 255,228,225 (lc 'Moccasin') => 0xFFE4B5, # 255,228,181 (lc 'NavajoWhite') => 0xFFDEAD, # 255,222,173 (lc 'Navy') => 0x000080, # 0,0,128 (lc 'OldLace') => 0xFDF5E6, # 253,245,230 (lc 'Olive') => 0x808000, # 128,128,0 (lc 'OliveDrab') => 0x6B8E23, # 107,142,35 (lc 'Orange') => 0xFFA500, # 255,165,0 (lc 'OrangeRed') => 0xFF4500, # 255,69,0 (lc 'Orchid') => 0xDA70D6, # 218,112,214 (lc 'PaleGoldenrod') => 0xEEE8AA, # 238,232,170 (lc 'PaleGreen') => 0x98FB98, # 152,251,152 (lc 'PaleTurquoise') => 0xAFEEEE, # 175,238,238 (lc 'PaleVioletRed') => 0xDB7093, # 219,112,147 (lc 'PapayaWhip') => 0xFFEFD5, # 255,239,213 (lc 'PeachPuff') => 0xFFDAB9, # 255,218,185 (lc 'Peru') => 0xCD853F, # 205,133,63 (lc 'Pink') => 0xFFC0CB, # 255,192,203 (lc 'Plum') => 0xDDA0DD, # 221,160,221 (lc 'PowderBlue') => 0xB0E0E6, # 176,224,230 (lc 'Purple') => 0x800080, # 128,0,128 (lc 'Red') => 0xFF0000, # 255,0,0 (lc 'RosyBrown') => 0xBC8F8F, # 188,143,143 (lc 'RoyalBlue') => 0x4169E1, # 65,105,225 (lc 'SaddleBrown') => 0x8B4513, # 139,69,19 (lc 'Salmon') => 0xFA8072, # 250,128,114 (lc 'SandyBrown') => 0xF4A460, # 244,164,96 (lc 'SeaGreen') => 0x2E8B57, # 46,139,87 (lc 'Seashell') => 0xFFF5EE, # 255,245,238 (lc 'Sienna') => 0xA0522D, # 160,82,45 (lc 'Silver') => 0xC0C0C0, # 192,192,192 (lc 'SkyBlue') => 0x87CEEB, # 135,206,235 (lc 'SlateBlue') => 0x6A5ACD, # 106,90,205 (lc 'SlateGray') => 0x708090, # 112,128,144 (lc 'Snow') => 0xFFFAFA, # 255,250,250 (lc 'SpringGreen') => 0x00FF7F, # 0,255,127 (lc 'SteelBlue') => 0x4682B4, # 70,130,180 (lc 'Tan') => 0xD2B48C, # 210,180,140 (lc 'Teal') => 0x008080, # 0,128,128 (lc 'Thistle') => 0xD8BFD8, # 216,191,216 (lc 'Tomato') => 0xFF6347, # 255,99,71 (lc 'Turquoise') => 0x40E0D0, # 64,224,208 (lc 'Violet') => 0xEE82EE, # 238,130,238 (lc 'Wheat') => 0xF5DEB3, # 245,222,179 (lc 'White') => 0xFFFFFF, # 255,255,255 (lc 'WhiteSmoke') => 0xF5F5F5, # 245,245,245 (lc 'Yellow') => 0xFFFF00, # 255,255,0 (lc 'YellowGreen') => 0x9ACD32, # 154,205,50 }; } 1; -__END__ +=encoding utf8 + +=head1 NAME + +Graphics::ColorNames::IE - MS Internet Explorer color names and equivalent RGB values + +=head1 SYNOPSIS + + require Graphics::ColorNames::IE; + + $NameTable = Graphics::ColorNames::IE->NamesRgbTable(); + $RgbBlack = $NameTable->{black}; + +=head1 DESCRIPTION + +This module defines color names and their associated RGB values recognized by +Microsoft Internet Explorer. + +=head2 NOTE + +Although Microsoft calls them "X11 color names", some of them are not identical +to the definitions in the X Specification. + +=head1 SEE ALSO + +C<Graphics::ColorNames>, MSDN <http://msdn.microsoft.com/library/en-us/dnwebgen/html/X11_names.asp> + +=head1 AUTHOR + +Claus Färber <CFAERBER@cpan.org> + +Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. + +=head1 LICENSE + +Copyright © 2005-2008 Claus Färber. + +Copyright © 2001-2004 Robert Rothenberg. + +All rights reserved. This program is free software; you can redistribute it +and/or modify it under the same terms as Perl itself. + +=cut diff --git a/lib/Graphics/ColorNames/SVG.pm b/lib/Graphics/ColorNames/SVG.pm new file mode 100644 index 0000000..69d1b08 --- /dev/null +++ b/lib/Graphics/ColorNames/SVG.pm @@ -0,0 +1,50 @@ +# $Id$ +# +package Graphics::ColorNames::SVG; + +require 5.006; + +use strict; +use warnings; + +use Graphics::ColorNames::WWW(); + +our $VERSION = '1.10'; + +*NamesRgbTable = \&Graphics::ColorNames::WWW::NamesRgbTable; + +1; + +=encoding utf8 + +=head1 NAME + +Graphics::ColorNames::SVG - SVG color names and equivalent RGB values + +=head1 SYNOPSIS + + require Graphics::ColorNames::SVG; + + $NameTable = Graphics::ColorNames::SVG->NamesRgbTable(); + $RgbBlack = $NameTable->{black}; + +=head1 DESCRIPTION + +This module defines color names and their associated RGB values +from the SVG 1.2 Specification. + +It is actually an alias for L<Graphic::ColorNames::WWW>. + +=head1 AUTHOR + +Claus Färber <CFAERBER@cpan.org> + +=head1 LICENSE + +Copyright © 2008 Claus Färber. + +All rights reserved. This program is free software; you can +redistribute it and/or modify it under the same terms as Perl +itself. + +=cut diff --git a/SVG.pm b/lib/Graphics/ColorNames/WWW.pm similarity index 92% rename from SVG.pm rename to lib/Graphics/ColorNames/WWW.pm index 5eb4f9f..1fffc9b 100644 --- a/SVG.pm +++ b/lib/Graphics/ColorNames/WWW.pm @@ -1,208 +1,216 @@ +# $Id$ +# package Graphics::ColorNames::SVG; -=head1 NAME - -Graphics::ColorNames::SVG - SVG color names and equivalent RGB values - -=head1 SYNOPSIS - - require Graphics::ColorNames::SVG; - - $NameTable = Graphics::ColorNames::SVG->NamesRgbTable(); - $RgbBlack = $NameTable->{black}; - -=head1 DESCRIPTION - -This module defines color names and their associated RGB values from the -SVG 1.2 Specification. - -=head2 Note - -Reportedly "fuchsia" was misspelled "fuscia" in an unidentified SVG -specification. It also appears to be a common misspelling, so both names are -recognized. - -=head1 SEE ALSO - -C<Graphics::ColorNames>, SVG 1.2 Specificiation <http://www.w3.org/SVG/> - -=head1 AUTHOR - -Claus Färber <CFAERBER@cpan.org> - -=head1 LICENSE - -Copyright © 2005-2008 Claus Färber - -Based on C<Graphics::ColorNames::HTML> Copyright © 2001-2004 Robert Rothenberg. - -All rights reserved. This program is free software; you can redistribute it -and/or modify it under the same terms as Perl itself. - -=cut - require 5.006; use strict; use warnings; -our $VERSION = '1.00'; +our $VERSION = '1.10'; sub NamesRgbTable() { sub rgb { ($_[0] << 16) + ($_[1] << 8) + ($_[2]) } use integer; return { 'aliceblue' => rgb(240, 248, 255), 'antiquewhite' => rgb(250, 235, 215), 'aqua' => rgb( 0, 255, 255), 'aquamarine' => rgb(127, 255, 212), 'azure' => rgb(240, 255, 255), 'beige' => rgb(245, 245, 220), 'bisque' => rgb(255, 228, 196), 'black' => rgb( 0, 0, 0), 'blanchedalmond' => rgb(255, 235, 205), 'blue' => rgb( 0, 0, 255), 'blueviolet' => rgb(138, 43, 226), 'brown' => rgb(165, 42, 42), 'burlywood' => rgb(222, 184, 135), 'cadetblue' => rgb( 95, 158, 160), 'chartreuse' => rgb(127, 255, 0), 'chocolate' => rgb(210, 105, 30), 'coral' => rgb(255, 127, 80), 'cornflowerblue' => rgb(100, 149, 237), 'cornsilk' => rgb(255, 248, 220), 'crimson' => rgb(220, 20, 60), 'cyan' => rgb( 0, 255, 255), 'darkblue' => rgb( 0, 0, 139), 'darkcyan' => rgb( 0, 139, 139), 'darkgoldenrod' => rgb(184, 134, 11), 'darkgray' => rgb(169, 169, 169), 'darkgreen' => rgb( 0, 100, 0), 'darkgrey' => rgb(169, 169, 169), 'darkkhaki' => rgb(189, 183, 107), 'darkmagenta' => rgb(139, 0, 139), 'darkolivegreen' => rgb( 85, 107, 47), 'darkorange' => rgb(255, 140, 0), 'darkorchid' => rgb(153, 50, 204), 'darkred' => rgb(139, 0, 0), 'darksalmon' => rgb(233, 150, 122), 'darkseagreen' => rgb(143, 188, 143), 'darkslateblue' => rgb( 72, 61, 139), 'darkslategray' => rgb( 47, 79, 79), 'darkslategrey' => rgb( 47, 79, 79), 'darkturquoise' => rgb( 0, 206, 209), 'darkviolet' => rgb(148, 0, 211), 'deeppink' => rgb(255, 20, 147), 'deepskyblue' => rgb( 0, 191, 255), 'dimgray' => rgb(105, 105, 105), 'dimgrey' => rgb(105, 105, 105), 'dodgerblue' => rgb( 30, 144, 255), 'firebrick' => rgb(178, 34, 34), 'floralwhite' => rgb(255, 250, 240), 'forestgreen' => rgb( 34, 139, 34), 'fuchsia' => 0xff00ff, # "fuscia" is incorrect but common 'fuscia' => 0xff00ff, # mis-spelling... 'gainsboro' => rgb(220, 220, 220), 'ghostwhite' => rgb(248, 248, 255), 'gold' => rgb(255, 215, 0), 'goldenrod' => rgb(218, 165, 32), 'gray' => rgb(128, 128, 128), 'grey' => rgb(128, 128, 128), 'green' => rgb( 0, 128, 0), 'greenyellow' => rgb(173, 255, 47), 'honeydew' => rgb(240, 255, 240), 'hotpink' => rgb(255, 105, 180), 'indianred' => rgb(205, 92, 92), 'indigo' => rgb( 75, 0, 130), 'ivory' => rgb(255, 255, 240), 'khaki' => rgb(240, 230, 140), 'lavender' => rgb(230, 230, 250), 'lavenderblush' => rgb(255, 240, 245), 'lawngreen' => rgb(124, 252, 0), 'lemonchiffon' => rgb(255, 250, 205), 'lightblue' => rgb(173, 216, 230), 'lightcoral' => rgb(240, 128, 128), 'lightcyan' => rgb(224, 255, 255), 'lightgoldenrodyellow' => rgb(250, 250, 210), 'lightgray' => rgb(211, 211, 211), 'lightgreen' => rgb(144, 238, 144), 'lightgrey' => rgb(211, 211, 211), 'lightpink' => rgb(255, 182, 193), 'lightsalmon' => rgb(255, 160, 122), 'lightseagreen' => rgb( 32, 178, 170), 'lightskyblue' => rgb(135, 206, 250), 'lightslategray' => rgb(119, 136, 153), 'lightslategrey' => rgb(119, 136, 153), 'lightsteelblue' => rgb(176, 196, 222), 'lightyellow' => rgb(255, 255, 224), 'lime' => rgb( 0, 255, 0), 'limegreen' => rgb( 50, 205, 50), 'linen' => rgb(250, 240, 230), 'magenta' => rgb(255, 0, 255), 'maroon' => rgb(128, 0, 0), 'mediumaquamarine' => rgb(102, 205, 170), 'mediumblue' => rgb( 0, 0, 205), 'mediumorchid' => rgb(186, 85, 211), 'mediumpurple' => rgb(147, 112, 219), 'mediumseagreen' => rgb( 60, 179, 113), 'mediumslateblue' => rgb(123, 104, 238), 'mediumspringgreen' => rgb( 0, 250, 154), 'mediumturquoise' => rgb( 72, 209, 204), 'mediumvioletred' => rgb(199, 21, 133), 'midnightblue' => rgb( 25, 25, 112), 'mintcream' => rgb(245, 255, 250), 'mistyrose' => rgb(255, 228, 225), 'moccasin' => rgb(255, 228, 181), 'navajowhite' => rgb(255, 222, 173), 'navy' => rgb( 0, 0, 128), 'oldlace' => rgb(253, 245, 230), 'olive' => rgb(128, 128, 0), 'olivedrab' => rgb(107, 142, 35), 'orange' => rgb(255, 165, 0), 'orangered' => rgb(255, 69, 0), 'orchid' => rgb(218, 112, 214), 'palegoldenrod' => rgb(238, 232, 170), 'palegreen' => rgb(152, 251, 152), 'paleturquoise' => rgb(175, 238, 238), 'palevioletred' => rgb(219, 112, 147), 'papayawhip' => rgb(255, 239, 213), 'peachpuff' => rgb(255, 218, 185), 'peru' => rgb(205, 133, 63), 'pink' => rgb(255, 192, 203), 'plum' => rgb(221, 160, 221), 'powderblue' => rgb(176, 224, 230), 'purple' => rgb(128, 0, 128), 'red' => rgb(255, 0, 0), 'rosybrown' => rgb(188, 143, 143), 'royalblue' => rgb( 65, 105, 225), 'saddlebrown' => rgb(139, 69, 19), 'salmon' => rgb(250, 128, 114), 'sandybrown' => rgb(244, 164, 96), 'seagreen' => rgb( 46, 139, 87), 'seashell' => rgb(255, 245, 238), 'sienna' => rgb(160, 82, 45), 'silver' => rgb(192, 192, 192), 'skyblue' => rgb(135, 206, 235), 'slateblue' => rgb(106, 90, 205), 'slategray' => rgb(112, 128, 144), 'slategrey' => rgb(112, 128, 144), 'snow' => rgb(255, 250, 250), 'springgreen' => rgb( 0, 255, 127), 'steelblue' => rgb( 70, 130, 180), 'tan' => rgb(210, 180, 140), 'teal' => rgb( 0, 128, 128), 'thistle' => rgb(216, 191, 216), 'tomato' => rgb(255, 99, 71), 'turquoise' => rgb( 64, 224, 208), 'violet' => rgb(238, 130, 238), 'wheat' => rgb(245, 222, 179), 'white' => rgb(255, 255, 255), 'whitesmoke' => rgb(245, 245, 245), 'yellow' => rgb(255, 255, 0), 'yellowgreen' => rgb(154, 205, 50), }; } 1; -__END__ +=encoding utf8 + +=head1 NAME + +Graphics::ColorNames::SVG - SVG color names and equivalent RGB values + +=head1 SYNOPSIS + + require Graphics::ColorNames::SVG; + + $NameTable = Graphics::ColorNames::SVG->NamesRgbTable(); + $RgbBlack = $NameTable->{black}; + +=head1 DESCRIPTION + +This module defines color names and their associated RGB values from +various WWW specifications, such as SVG or CSS. + + +=head2 Note + +Reportedly "fuchsia" was misspelled "fuscia" in an unidentified HTML +specification. It also appears to be a common misspelling, so both names are +recognized. + +=head1 SEE ALSO + +C<Graphics::ColorNames>, +SVG 1.2 Specificiation <http://www.w3.org/SVG/>, +CSS Color Module Level 3 <http://www.w3.org/TR/css3-color>. + +=head1 AUTHOR + +Claus Färber <CFAERBER@cpan.org> + +Based on C<Graphics::ColorNames::HTML> by Robert Rothenberg. + +=head1 LICENSE + +Copyright © 2005-2008 Claus Färber. + +Copyright © 2001-2004 Robert Rothenberg. + +All rights reserved. This program is free software; you can +redistribute it and/or modify it under the same terms as Perl +itself. + +=cut diff --git a/t/10pod.t b/t/10pod.t new file mode 100644 index 0000000..c3073fe --- /dev/null +++ b/t/10pod.t @@ -0,0 +1,9 @@ +# $Id$ + +use strict; +use Test::More; + +eval "use Test::Pod 1.00"; +plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; + +all_pod_files_ok(); diff --git a/t/11pod_cover.t b/t/11pod_cover.t new file mode 100644 index 0000000..f10ca82 --- /dev/null +++ b/t/11pod_cover.t @@ -0,0 +1,15 @@ +# $Id$ + +use strict; +use Test::More; + +eval "use Test::Pod::Coverage;"; +plan skip_all => "Test::Pod::Coverage required for testing POD coverage" if $@; + +plan tests => 2; + +pod_coverage_ok( 'Color::Calc', { + trustme => [ qr/_(tuple|html|pdf|hex|obj|object)$/, qr/^color(_.+)?$/ ], + }, 'Color::Calc is covered by POD' ); + +pod_coverage_ok( 'Color::Calc::WWW', 'Color::Calc::WWW is covered by POD' ); diff --git a/t/CSS.t b/t/CSS.t new file mode 100644 index 0000000..0d4afa8 --- /dev/null +++ b/t/CSS.t @@ -0,0 +1,18 @@ +use Test; + +BEGIN { + plan tests => 5, todo => [ ] +} + +use strict; +use Carp; + +use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); +ok(1); + +tie my %colors, 'Graphics::ColorNames', 'CSS'; +ok(1); + +ok(exists($colors{"fuchsia"})); +ok(exists($colors{"fuscia"})); +ok($colors{"fuscia"} eq $colors{"fuchsia"}); diff --git a/t/11_IE.t b/t/IExplore.t similarity index 100% rename from t/11_IE.t rename to t/IExplore.t diff --git a/t/10_SVG.t b/t/SVG.t similarity index 100% rename from t/10_SVG.t rename to t/SVG.t diff --git a/t/00_WWW.t b/t/WWW.t similarity index 100% rename from t/00_WWW.t rename to t/WWW.t diff --git a/t/WWW_CSS.t b/t/WWW_CSS.t new file mode 100644 index 0000000..a6be0ff --- /dev/null +++ b/t/WWW_CSS.t @@ -0,0 +1,21 @@ +use Test; + + +BEGIN { + my $colors = 148; + plan tests => $colors, todo => [ ] +} + +use strict; +use Carp; + +use Graphics::ColorNames 0.20, qw( hex2tuple tuple2hex ); +tie my %col_www, 'Graphics::ColorNames', 'WWW'; +tie my %colors, 'Graphics::ColorNames', 'CSS'; + +my $count = 0; +foreach my $name (keys %colors) + { + my @RGB = hex2tuple( $colors{$name} ); + ok(tuple2hex(@RGB), $col_www{$name} ); + } diff --git a/t/20_WWW_HTML.t b/t/WWW_HTML.t similarity index 100% rename from t/20_WWW_HTML.t rename to t/WWW_HTML.t diff --git a/t/20_WWW_IE.t b/t/WWW_IExplore.t similarity index 100% rename from t/20_WWW_IE.t rename to t/WWW_IExplore.t diff --git a/t/20_WWW_Mozilla.t b/t/WWW_Mozilla.t similarity index 100% rename from t/20_WWW_Mozilla.t rename to t/WWW_Mozilla.t diff --git a/t/20_WWW_SVG.t b/t/WWW_SVG.t similarity index 100% rename from t/20_WWW_SVG.t rename to t/WWW_SVG.t