repo
stringlengths 5
75
| commit
stringlengths 40
40
| message
stringlengths 6
18.2k
| diff
stringlengths 60
262k
|
---|---|---|---|
wsmoak/npanday-wix-plugin | 507aa9336e98e304b71d2d3d43691316b0e6833e | Allow user to give a list of .wxs files instead of just one. | diff --git a/src/it/IT001/pom.xml b/src/it/IT001/pom.xml
index 7bbf9a2..01fca4a 100755
--- a/src/it/IT001/pom.xml
+++ b/src/it/IT001/pom.xml
@@ -1,27 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>npanday.examples</groupId>
<artifactId>IT001</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>NPanday WiX Plugin Integation Test 001</name>
<description>
Simple integration test to execute candle on a sample .wxs file.
Based on tutorial at http://www.tramontana.co.hu/wix/
</description>
<build>
<plugins>
<plugin>
<groupId>npanday.plugin</groupId>
<artifactId>npanday-wix-plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<configuration>
- <sourceFile>Sample.wxs</sourceFile>
+ <sourceFiles>
+ <sourceFile>Sample.wxs</sourceFile>
+ </sourceFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>
diff --git a/src/main/java/npanday/plugin/wix/CandleMojo.java b/src/main/java/npanday/plugin/wix/CandleMojo.java
index 4917ba2..d163e9a 100755
--- a/src/main/java/npanday/plugin/wix/CandleMojo.java
+++ b/src/main/java/npanday/plugin/wix/CandleMojo.java
@@ -1,71 +1,75 @@
package npanday.plugin.wix;
/*
* Copyright ---
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import java.io.File;
import java.io.IOException;
/**
* Goal which executes WiX candle to create a .wixobj file.
*
* @goal candle
*
* @phase package
*/
public class CandleMojo
extends AbstractMojo
{
/**
* Location of the WiX source file.
* @parameter expression="${sourceFile}"
* @required
*/
- private File sourceFile;
+ private File[] sourceFiles;
public void execute()
throws MojoExecutionException
{
- File f = sourceFile;
-
- if ( !f.exists() )
- {
- throw new MojoExecutionException( "Source file does not exist " + sourceFile );
+ String paths = "";
+ for (int x = 0; x < sourceFiles.length; x++) {
+ File f = sourceFiles[x];
+ if ( !f.exists() )
+ {
+ throw new MojoExecutionException( "Source file does not exist " + sourceFiles[x] );
+ } else {
+ paths = paths + sourceFiles[x].getAbsolutePath() + " ";
+ }
}
try {
- String line = "candle " + sourceFile.getAbsolutePath();
+ String line = "candle " + paths;
CommandLine commandLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(commandLine);
if ( exitValue != 0 ) {
throw new MojoExecutionException( "Problem executing candle, return code " + exitValue );
}
} catch (ExecuteException e) {
throw new MojoExecutionException( "Problem executing candle", e );
} catch (IOException e ) {
throw new MojoExecutionException( "Problem executing candle", e );
}
}
}
diff --git a/src/site/apt/usage/candle.apt b/src/site/apt/usage/candle.apt
index b4156ab..5a2dbd7 100644
--- a/src/site/apt/usage/candle.apt
+++ b/src/site/apt/usage/candle.apt
@@ -1,33 +1,35 @@
-----
Candle Mojo Usage
-----
Candle Mojo Usage
Brief examples on how to use the candle goal.
* The <<<candle>>> mojo
If you want to convert a WiX Source (.wxs) file into a WiX Object (.wixobj) file, use this configuration in your pom:
+---+
<project>
...
<build>
<plugins>
<plugin>
<groupId>npanday.plugin</groupId>
<artifactId>npanday-wix-plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<configuration>
- <sourceFile>Sample.wxs</sourceFile>
+ <sourceFiles>
+ <sourceFile>Sample.wxs</sourceFile>
+ </sourceFiles>
</configuration>
</plugin>
</plugins>
...
</build>
...
</project>
+---+
Generally this will be done in a separate module with pom packaging.
\ No newline at end of file
|
wsmoak/npanday-wix-plugin | ce22fc27a1459f53a43d3ecc4c79dc121d1f3d0a | Add .tmproj to ignores | diff --git a/.gitignore b/.gitignore
index 73df60d..7af8963 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
target
.classpath
.project
.settings
+*.tmproj
|
wsmoak/npanday-wix-plugin | 76b8cf36fada787c2d3d7d5f8cfaaa6c05ca6da8 | Add a mojo and integration test for the WiX 'light' command | diff --git a/src/it/IT002/Helper.dll b/src/it/IT002/Helper.dll
new file mode 100644
index 0000000..e69de29
diff --git a/src/it/IT002/Manual.pdf b/src/it/IT002/Manual.pdf
new file mode 100644
index 0000000..e69de29
diff --git a/src/it/IT002/Sample.wixobj b/src/it/IT002/Sample.wixobj
new file mode 100755
index 0000000..52e8bef
--- /dev/null
+++ b/src/it/IT002/Sample.wixobj
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="utf-8"?><wixObject xmlns="http://schemas.microsoft.com/wix/2003/04/objects" src="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs" version="2.0.2207.0"><section id="6E390708-A2AD-4269-8CE0-561D72DFCFF3" type="product" codepage="1252"><reference table="Component" symbol="HelperLibrary" /><reference table="Component" symbol="MainExecutable" /><reference table="Component" symbol="Manual" /><reference table="Directory" symbol="DesktopFolder" /><reference table="Directory" symbol="ProgramMenuDir" /><reference table="Icon" symbol="Thing10.exe" /><reference table="Media" symbol="1" /><reference table="Property" symbol="DiskPrompt" /><complexReference parentType="feature" parent="Complete" childType="component" child="MainExecutable" /><complexReference parentType="feature" parent="Complete" childType="component" child="HelperLibrary" /><complexReference parentType="feature" parent="Complete" childType="component" child="Manual" /><table name="File"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*19"><field>ThingEXE</field><field>MainExecutable</field><field>Thing10.exe|ThingAppl10.exe</field><field>0</field><field /><field /><field>512</field><field /><field /><field /><field /><field>INSTALLDIR</field><field>1</field><field>ThingAppl10.exe</field><field /><field>-1</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*30"><field>HelperDLL</field><field>HelperLibrary</field><field>Helper.dll</field><field>0</field><field /><field /><field>512</field><field /><field /><field /><field /><field>INSTALLDIR</field><field>1</field><field>Helper.dll</field><field /><field>-1</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*34"><field>Manual</field><field>Manual</field><field>Manual.pdf</field><field>0</field><field /><field /><field>0</field><field /><field /><field /><field /><field>INSTALLDIR</field><field>1</field><field>Manual.pdf</field><field /><field>-1</field></tuple></table><table name="RemoveFile"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*26"><field>ProgramMenuDir</field><field>MainExecutable</field><field /><field>INSTALLDIR</field><field>2</field></tuple></table><table name="Property"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*3"><field>Manufacturer</field><field>Sample Inc.</field><field>0</field><field>0</field><field>0</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*3"><field>ProductCode</field><field>{6E390708-A2AD-4269-8CE0-561D72DFCFF3}</field><field>0</field><field>0</field><field>0</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*3"><field>ProductLanguage</field><field>1033</field><field>0</field><field>0</field><field>0</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*3"><field>ProductName</field><field>Thing 1.0</field><field>0</field><field>0</field><field>0</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*3"><field>ProductVersion</field><field>1.0.0</field><field>0</field><field>0</field><field>0</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*12"><field>DiskPrompt</field><field>Sample's Thing 1.0 Installation [1]</field><field>0</field><field>0</field><field>0</field></tuple></table><table name="Directory"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*16"><field>INSTALLDIR</field><field>Sample</field><field>Thing10|Thing 1.0</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*15"><field>Sample</field><field>ProgramFilesFolder</field><field>Sample</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*14"><field>ProgramFilesFolder</field><field>TARGETDIR</field><field>PFiles</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*44"><field>ProgramMenuDir</field><field>ProgramMenuFolder</field><field>Thing10|Thing 1.0</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*43"><field>ProgramMenuFolder</field><field>TARGETDIR</field><field>PMenu|Programs</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*47"><field>DesktopFolder</field><field>TARGETDIR</field><field>Desktop</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*13"><field>TARGETDIR</field><field /><field>SourceDir</field></tuple></table><table name="Media"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*11"><field>1</field><field>0</field><field>CD-ROM #1</field><field>#Sample.cab</field><field /><field /><field /><field /></tuple></table><table name="Feature"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*50"><field>Complete</field><field /><field /><field /><field>2</field><field>1</field><field /><field>0</field></tuple></table><table name="Icon"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*56"><field>Thing10.exe</field><field>ThingAppl10.exe</field></tuple></table><table name="_SummaryInformation"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>1</field><field>1252</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>2</field><field>Installation Database</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>3</field><field>Sample Inc's Thing 1.0 Installer</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>4</field><field>Sample Inc.</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>5</field><field>Installer</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>6</field><field>Thing is a registered trademark of Sample Inc.</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>7</field><field>;1033</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>9</field><field>{5902BCD6-12B9-4F38-BF6B-2C30F825FFED}</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>14</field><field>100</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>15</field><field>2</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*6"><field>19</field><field>2</field></tuple></table><table name="Shortcut"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*21"><field>startmenuThing10</field><field>ProgramMenuDir</field><field>Thing10|Thing 1.0</field><field>MainExecutable</field><field>[#ThingEXE]</field><field /><field /><field /><field>Thing10.exe</field><field>0</field><field /><field>INSTALLDIR</field><field /><field /><field /><field /></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*23"><field>desktopThing10</field><field>DesktopFolder</field><field>Thing10|Thing 1.0</field><field>MainExecutable</field><field>[#ThingEXE]</field><field /><field /><field /><field>Thing10.exe</field><field>0</field><field /><field>INSTALLDIR</field><field /><field /><field /><field /></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*35"><field>startmenuManual</field><field>ProgramMenuDir</field><field>Manual|Instruction Manual</field><field>Manual</field><field>[#Manual]</field><field /><field /><field /><field /><field /><field /><field /><field /><field /><field /><field /></tuple></table><table name="Component"><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*18"><field>MainExecutable</field><field>{059035F2-A47C-4407-8459-0597276DF276}</field><field>INSTALLDIR</field><field>0</field><field /><field>ThingEXE</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*29"><field>HelperLibrary</field><field>{DFEB88F1-A60F-45E9-80F1-1AB62E66D73C}</field><field>INSTALLDIR</field><field>0</field><field /><field>HelperDLL</field></tuple><tuple sourceLineNumber="F:\git\npanday-wix-plugin\target\it\IT001\Sample.wxs*33"><field>Manual</field><field>{B6277FF6-CA9E-481E-9619-758FD725A752}</field><field>INSTALLDIR</field><field>0</field><field /><field>Manual</field></tuple></table></section></wixObject>
\ No newline at end of file
diff --git a/src/it/IT002/ThingAppl10.exe b/src/it/IT002/ThingAppl10.exe
new file mode 100644
index 0000000..e69de29
diff --git a/src/it/IT002/goals.txt b/src/it/IT002/goals.txt
new file mode 100755
index 0000000..8298fe8
--- /dev/null
+++ b/src/it/IT002/goals.txt
@@ -0,0 +1 @@
+npanday.plugin:npanday-wix-plugin:light
diff --git a/src/it/IT002/pom.xml b/src/it/IT002/pom.xml
new file mode 100755
index 0000000..d6ad57d
--- /dev/null
+++ b/src/it/IT002/pom.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://maven.apache.org/POM/4.0.0">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>npanday.examples</groupId>
+ <artifactId>IT002</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+ <name>NPanday WiX Plugin Integation Test 002</name>
+ <description>
+ Simple integration test to execute light on a sample .wixobj file.
+ Based on tutorial at http://www.tramontana.co.hu/wix/
+ </description>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>npanday.plugin</groupId>
+ <artifactId>npanday-wix-plugin</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <configuration>
+ <objectFile>Sample.wixobj</objectFile>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
diff --git a/src/it/IT002/verify.bsh b/src/it/IT002/verify.bsh
new file mode 100755
index 0000000..6a0e5d3
--- /dev/null
+++ b/src/it/IT002/verify.bsh
@@ -0,0 +1,18 @@
+import java.io.*;
+
+try
+{
+ File file = new File( basedir, "Sample.wixobj" );
+ if ( !file.isFile() )
+ {
+ System.err.println( "Could not find WiX Object File: " + file );
+ return false;
+ }
+}
+catch( Throwable t )
+{
+ t.printStackTrace();
+ return false;
+}
+
+return true;
diff --git a/src/main/java/npanday/plugin/wix/LightMojo.java b/src/main/java/npanday/plugin/wix/LightMojo.java
new file mode 100755
index 0000000..3ae418a
--- /dev/null
+++ b/src/main/java/npanday/plugin/wix/LightMojo.java
@@ -0,0 +1,71 @@
+package npanday.plugin.wix;
+
+/*
+ * Copyright ---
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.commons.exec.CommandLine;
+import org.apache.commons.exec.DefaultExecutor;
+import org.apache.commons.exec.ExecuteException;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Goal which executes WiX light to create a .msi file.
+ *
+ * @goal light
+ *
+ * @phase package
+ */
+public class LightMojo
+ extends AbstractMojo
+{
+ /**
+ * Location of the WiX object file.
+ * @parameter expression="${objectFile}"
+ * @required
+ */
+ private File objectFile;
+
+ public void execute()
+ throws MojoExecutionException
+ {
+ File f = objectFile;
+
+ if ( !f.exists() )
+ {
+ throw new MojoExecutionException( "Source file does not exist " + objectFile );
+ }
+
+ try {
+ String line = "light " + objectFile.getAbsolutePath();
+ CommandLine commandLine = CommandLine.parse(line);
+ DefaultExecutor executor = new DefaultExecutor();
+ int exitValue = executor.execute(commandLine);
+
+ if ( exitValue != 0 ) {
+ throw new MojoExecutionException( "Problem executing candle, return code " + exitValue );
+ }
+
+ } catch (ExecuteException e) {
+ throw new MojoExecutionException( "Problem executing candle", e );
+ } catch (IOException e ) {
+ throw new MojoExecutionException( "Problem executing candle", e );
+ }
+ }
+}
|
wsmoak/npanday-wix-plugin | fc5a105e66342a1ff67113c7e77386b3f8d582ed | Use Commons Exec to execute candle on the supplied source file. | diff --git a/pom.xml b/pom.xml
index 73abc9f..81dbc41 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,23 +1,28 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>npanday.plugin</groupId>
<artifactId>npanday-wix-plugin</artifactId>
<packaging>maven-plugin</packaging>
<version>1.0-SNAPSHOT</version>
<name>npanday-wix-plugin Maven Mojo</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-exec</artifactId>
+ <version>1.0</version>
+ </dependency>
</dependencies>
</project>
diff --git a/src/main/java/npanday/plugin/wix/CandleMojo.java b/src/main/java/npanday/plugin/wix/CandleMojo.java
index 6f5bf2a..4917ba2 100755
--- a/src/main/java/npanday/plugin/wix/CandleMojo.java
+++ b/src/main/java/npanday/plugin/wix/CandleMojo.java
@@ -1,56 +1,71 @@
package npanday.plugin.wix;
/*
* Copyright ---
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+import org.apache.commons.exec.CommandLine;
+import org.apache.commons.exec.DefaultExecutor;
+import org.apache.commons.exec.ExecuteException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import java.io.File;
-import java.io.FileWriter;
import java.io.IOException;
/**
* Goal which executes WiX candle to create a .wixobj file.
*
* @goal candle
*
* @phase package
*/
public class CandleMojo
extends AbstractMojo
{
/**
* Location of the WiX source file.
* @parameter expression="${sourceFile}"
* @required
*/
private File sourceFile;
public void execute()
throws MojoExecutionException
{
File f = sourceFile;
if ( !f.exists() )
{
throw new MojoExecutionException( "Source file does not exist " + sourceFile );
}
- //TODO: execute candle
-
+ try {
+ String line = "candle " + sourceFile.getAbsolutePath();
+ CommandLine commandLine = CommandLine.parse(line);
+ DefaultExecutor executor = new DefaultExecutor();
+ int exitValue = executor.execute(commandLine);
+
+ if ( exitValue != 0 ) {
+ throw new MojoExecutionException( "Problem executing candle, return code " + exitValue );
+ }
+
+ } catch (ExecuteException e) {
+ throw new MojoExecutionException( "Problem executing candle", e );
+ } catch (IOException e ) {
+ throw new MojoExecutionException( "Problem executing candle", e );
+ }
}
}
|
wsmoak/npanday-wix-plugin | abe21043d6d0a414a8acced5886e9c1dea7cdd7c | Fix description | diff --git a/src/main/java/npanday/plugin/wix/CandleMojo.java b/src/main/java/npanday/plugin/wix/CandleMojo.java
old mode 100644
new mode 100755
index c4bbe8e..6f5bf2a
--- a/src/main/java/npanday/plugin/wix/CandleMojo.java
+++ b/src/main/java/npanday/plugin/wix/CandleMojo.java
@@ -1,5 +1,56 @@
package npanday.plugin.wix;
-public class CandleMojo {
+/*
+ * Copyright ---
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+
+/**
+ * Goal which executes WiX candle to create a .wixobj file.
+ *
+ * @goal candle
+ *
+ * @phase package
+ */
+public class CandleMojo
+ extends AbstractMojo
+{
+ /**
+ * Location of the WiX source file.
+ * @parameter expression="${sourceFile}"
+ * @required
+ */
+ private File sourceFile;
+
+ public void execute()
+ throws MojoExecutionException
+ {
+ File f = sourceFile;
+
+ if ( !f.exists() )
+ {
+ throw new MojoExecutionException( "Source file does not exist " + sourceFile );
+ }
+
+ //TODO: execute candle
+
+ }
}
|
wsmoak/npanday-wix-plugin | 9e11205f94603d3bd3f93f04afad9612005173fc | Integration test for candle mojo, should produce .wixobj file. | diff --git a/src/it/IT001/SampleFirst.wxs b/src/it/IT001/SampleFirst.wxs
new file mode 100755
index 0000000..8c7b3ea
--- /dev/null
+++ b/src/it/IT001/SampleFirst.wxs
@@ -0,0 +1,60 @@
+<?xml version='1.0' encoding='windows-1252'?>
+<Wix xmlns='http://schemas.microsoft.com/wix/2003/01/wi'>
+ <Product Name='Foobar 1.0' Id='6E390708-A2AD-4269-8CE0-561D72DFCFF3'
+ Language='1033' Codepage='1252' Version='1.0.0' Manufacturer='Acme Ltd.'>
+
+ <Package Id='5902BCD6-12B9-4F38-BF6B-2C30F825FFED' Keywords='Installer'
+ Description="Acme's Foobar 1.0 Installer"
+ Comments='Foobar is a registered trademark of Acme Ltd.' Manufacturer='Acme Ltd.'
+ InstallerVersion='100' Languages='1033' Compressed='yes' SummaryCodepage='1252' />
+
+ <Media Id='1' Cabinet='Sample.cab' EmbedCab='yes' DiskPrompt="CD-ROM #1" />
+ <Property Id='DiskPrompt' Value="Acme's Foobar 1.0 Installation [1]" />
+
+ <Directory Id='TARGETDIR' Name='SourceDir'>
+ <Directory Id='ProgramFilesFolder' Name='PFiles'>
+ <Directory Id='Acme' Name='Acme'>
+ <Directory Id='INSTALLDIR' Name='Foobar10' LongName='Foobar 1.0'>
+
+ <Component Id='MainExecutable' Guid='059035F2-A47C-4407-8459-0597276DF276'>
+ <File Id='FoobarEXE' Name='Foobar10.exe' LongName='FoobarAppl10.exe' DiskId='1'
+ Source='FoobarAppl10.exe' Vital='yes'>
+ <Shortcut Id="startmenuFoobar10" Directory="ProgramMenuDir" Name="Foobar10"
+ LongName="Foobar 1.0" WorkingDirectory='INSTALLDIR' Icon="Foobar10.exe" IconIndex="0" />
+ <Shortcut Id="desktopFoobar10" Directory="DesktopFolder" Name="Foobar10"
+ LongName="Foobar 1.0" WorkingDirectory='INSTALLDIR' Icon="Foobar10.exe" IconIndex="0" />
+ </File>
+ <RemoveFolder Id='ProgramMenuDir' On='uninstall' />
+ </Component>
+
+ <Component Id='HelperLibrary' Guid='DFEB88F1-A60f-45E9-80F1-1AB62E66D73C'>
+ <File Id='HelperDLL' Name='Helper.dll' DiskId='1' Source='Helper.dll' Vital='yes' />
+ </Component>
+
+ <Component Id='Manual' Guid='B6277FF6-CA9E-481E-9619-758FD725A752'>
+ <File Id='Manual' Name='Manual.pdf' DiskId='1' Source='Manual.pdf'>
+ <Shortcut Id="startmenuManual" Directory="ProgramMenuDir" Name="Manual" LongName="Instruction Manual" />
+ </File>
+ </Component>
+
+ </Directory>
+ </Directory>
+ </Directory>
+
+ <Directory Id="ProgramMenuFolder" Name="PMenu" LongName="Programs">
+ <Directory Id="ProgramMenuDir" Name='Foobar10' LongName="Foobar 1.0" />
+ </Directory>
+
+ <Directory Id="DesktopFolder" Name="Desktop" />
+ </Directory>
+
+ <Feature Id='Complete' Level='1'>
+ <ComponentRef Id='MainExecutable' />
+ <ComponentRef Id='HelperLibrary' />
+ <ComponentRef Id='Manual' />
+ </Feature>
+
+ <Icon Id="Foobar10.exe" SourceFile="FoobarAppl10.exe" />
+
+ </Product>
+</Wix>
diff --git a/src/it/IT001/pom.xml b/src/it/IT001/pom.xml
new file mode 100755
index 0000000..8cf481e
--- /dev/null
+++ b/src/it/IT001/pom.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://maven.apache.org/POM/4.0.0">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>npanday.examples</groupId>
+ <artifactId>IT001</artifactId>
+ <packaging>pom</packaging>
+ <name>NPanday WiX Plugin Integation Test 001</name>
+ <version>1.0-SNAPSHOT</version>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>npanday.plugin</groupId>
+ <artifactId>npanday-wix-plugin</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <configuration>
+ <sourceFile>SampleFirst.wxs</sourceFile>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
|
wsmoak/npanday-wix-plugin | 97bb09f2c7bb7535a09ab2184a471ba6426cc818 | Remove generated file and add mojo to execute candle. | diff --git a/src/main/java/npanday/plugin/wix/CandleMojo.java b/src/main/java/npanday/plugin/wix/CandleMojo.java
new file mode 100644
index 0000000..c4bbe8e
--- /dev/null
+++ b/src/main/java/npanday/plugin/wix/CandleMojo.java
@@ -0,0 +1,5 @@
+package npanday.plugin.wix;
+
+public class CandleMojo {
+
+}
diff --git a/src/main/java/npanday/plugin/wix/MyMojo.java b/src/main/java/npanday/plugin/wix/MyMojo.java
deleted file mode 100644
index fbf5d35..0000000
--- a/src/main/java/npanday/plugin/wix/MyMojo.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package npanday.plugin.wix;
-
-/*
- * Copyright 2001-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.apache.maven.plugin.AbstractMojo;
-import org.apache.maven.plugin.MojoExecutionException;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-
-/**
- * Goal which touches a timestamp file.
- *
- * @goal touch
- *
- * @phase process-sources
- */
-public class MyMojo
- extends AbstractMojo
-{
- /**
- * Location of the file.
- * @parameter expression="${project.build.directory}"
- * @required
- */
- private File outputDirectory;
-
- public void execute()
- throws MojoExecutionException
- {
- File f = outputDirectory;
-
- if ( !f.exists() )
- {
- f.mkdirs();
- }
-
- File touch = new File( f, "touch.txt" );
-
- FileWriter w = null;
- try
- {
- w = new FileWriter( touch );
-
- w.write( "touch.txt" );
- }
- catch ( IOException e )
- {
- throw new MojoExecutionException( "Error creating file " + touch, e );
- }
- finally
- {
- if ( w != null )
- {
- try
- {
- w.close();
- }
- catch ( IOException e )
- {
- // ignore
- }
- }
- }
- }
-}
|
wsmoak/npanday-wix-plugin | 6b6c4e798d41dac7ebd7463676e234189ace4b48 | Add skeleton plugin created from archetype | diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..73abc9f
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,23 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>npanday.plugin</groupId>
+ <artifactId>npanday-wix-plugin</artifactId>
+ <packaging>maven-plugin</packaging>
+ <version>1.0-SNAPSHOT</version>
+ <name>npanday-wix-plugin Maven Mojo</name>
+ <url>http://maven.apache.org</url>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-plugin-api</artifactId>
+ <version>2.0</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>3.8.1</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/src/main/java/npanday/plugin/wix/MyMojo.java b/src/main/java/npanday/plugin/wix/MyMojo.java
new file mode 100644
index 0000000..fbf5d35
--- /dev/null
+++ b/src/main/java/npanday/plugin/wix/MyMojo.java
@@ -0,0 +1,81 @@
+package npanday.plugin.wix;
+
+/*
+ * Copyright 2001-2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+
+/**
+ * Goal which touches a timestamp file.
+ *
+ * @goal touch
+ *
+ * @phase process-sources
+ */
+public class MyMojo
+ extends AbstractMojo
+{
+ /**
+ * Location of the file.
+ * @parameter expression="${project.build.directory}"
+ * @required
+ */
+ private File outputDirectory;
+
+ public void execute()
+ throws MojoExecutionException
+ {
+ File f = outputDirectory;
+
+ if ( !f.exists() )
+ {
+ f.mkdirs();
+ }
+
+ File touch = new File( f, "touch.txt" );
+
+ FileWriter w = null;
+ try
+ {
+ w = new FileWriter( touch );
+
+ w.write( "touch.txt" );
+ }
+ catch ( IOException e )
+ {
+ throw new MojoExecutionException( "Error creating file " + touch, e );
+ }
+ finally
+ {
+ if ( w != null )
+ {
+ try
+ {
+ w.close();
+ }
+ catch ( IOException e )
+ {
+ // ignore
+ }
+ }
+ }
+ }
+}
|
nipuL/pkgutils | b9913a29de27591584dad859dc429f42f6fa17fe | Bumped version to 5.33.0. | diff --git a/Makefile b/Makefile
index 0dd5406..172b7e9 100644
--- a/Makefile
+++ b/Makefile
@@ -1,101 +1,101 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
-VERSION = 5.32.0
+VERSION = 5.33.0
NAME = pkgutils-$(VERSION)
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDFLAGS += -static -larchive -lz -lbz2
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8 pkgmk.conf.5
all: pkgadd pkgmk rejmerge man
pkgadd: .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
rm -rf $(NAME) $(NAME).tar.gz
git archive --format=tar --prefix=$(NAME)/ HEAD | tar -x
git log > $(NAME)/ChangeLog
tar czvf $(NAME).tar.gz $(NAME)
rm -rf $(NAME)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
install -D -m0644 pkgmk.conf.5 $(DESTDIR)$(MANDIR)/man5/pkgmk.conf.5
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
# End of file
|
nipuL/pkgutils | 7b3f9929cba16da56f011ba666ca336b1cad2b28 | Bug #336: Only accept http/https/ftp/file protocols in sources. | diff --git a/pkgmk.in b/pkgmk.in
index 00d8e95..9fdf768 100755
--- a/pkgmk.in
+++ b/pkgmk.in
@@ -1,555 +1,553 @@
#!/bin/bash
#
# pkgutils
#
# Copyright (c) 2000-2005 Per Liden
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
info() {
echo "=======> $1"
}
warning() {
info "WARNING: $1" >&2
}
error() {
info "ERROR: $1" >&2
}
get_filename() {
- local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
-
- if [ "$FILE" != "$1" ]; then
- FILE="$PKGMK_SOURCE_DIR/$FILE"
+ if [[ $1 =~ ^(http|https|ftp|file)://.*/(.+) ]]; then
+ echo "$PKGMK_SOURCE_DIR/${BASH_REMATCH[2]}"
+ else
+ echo $1
fi
-
- echo $FILE
}
get_basename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
echo $FILE
}
check_pkgfile() {
if [ ! "$name" ]; then
error "Variable 'name' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$version" ]; then
error "Variable 'version' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$release" ]; then
error "Variable 'release' not specified in $PKGMK_PKGFILE."
exit 1
elif [ "`type -t build`" != "function" ]; then
error "Function 'build' not specified in $PKGMK_PKGFILE."
exit 1
fi
}
check_directory() {
if [ ! -d $1 ]; then
error "Directory '$1' does not exist."
exit 1
elif [ ! -w $1 ]; then
error "Directory '$1' not writable."
exit 1
elif [ ! -x $1 ] || [ ! -r $1 ]; then
error "Directory '$1' not readable."
exit 1
fi
}
download_file() {
info "Downloading '$1'."
if [ ! "`type -p wget`" ]; then
error "Command 'wget' not found."
exit 1
fi
LOCAL_FILENAME=`get_filename $1`
LOCAL_FILENAME_PARTIAL="$LOCAL_FILENAME.partial"
DOWNLOAD_OPTS="--passive-ftp --no-directories --tries=3 --waitretry=3 \
--directory-prefix=$PKGMK_SOURCE_DIR \
--output-document=$LOCAL_FILENAME_PARTIAL --no-check-certificate"
if [ -f "$LOCAL_FILENAME_PARTIAL" ]; then
info "Partial download found, trying to resume"
RESUME_CMD="-c"
fi
error=1
BASENAME=`get_basename $1`
for REPO in ${PKGMK_SOURCE_MIRRORS[@]}; do
REPO="`echo $REPO | sed 's|/$||'`"
wget $RESUME_CMD $DOWNLOAD_OPTS $PKGMK_WGET_OPTS $REPO/$BASENAME
error=$?
if [ $error == 0 ]; then
break
fi
done
if [ $error != 0 ]; then
while true; do
wget $RESUME_CMD $DOWNLOAD_OPTS $PKGMK_WGET_OPTS $1
error=$?
if [ $error != 0 ] && [ "$RESUME_CMD" ]; then
info "Partial download failed, restarting"
rm -f "$LOCAL_FILENAME_PARTIAL"
RESUME_CMD=""
else
break
fi
done
fi
if [ $error != 0 ]; then
error "Downloading '$1' failed."
exit 1
fi
mv -f "$LOCAL_FILENAME_PARTIAL" "$LOCAL_FILENAME"
}
download_source() {
local FILE LOCAL_FILENAME
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ ! -e $LOCAL_FILENAME ]; then
if [ "$LOCAL_FILENAME" = "$FILE" ]; then
error "Source file '$LOCAL_FILENAME' not found (can not be downloaded, URL not specified)."
exit 1
else
if [ "$PKGMK_DOWNLOAD" = "yes" ]; then
download_file $FILE
else
error "Source file '$LOCAL_FILENAME' not found (use option -d to download)."
exit 1
fi
fi
fi
done
}
unpack_source() {
local FILE LOCAL_FILENAME COMMAND
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
case $LOCAL_FILENAME in
*.tar.gz|*.tar.Z|*.tgz)
COMMAND="tar -C $SRC --use-compress-program=gzip -xf $LOCAL_FILENAME" ;;
*.tar.bz2)
COMMAND="tar -C $SRC --use-compress-program=bzip2 -xf $LOCAL_FILENAME" ;;
*.zip)
COMMAND="unzip -qq -o -d $SRC $LOCAL_FILENAME" ;;
*)
COMMAND="cp $LOCAL_FILENAME $SRC" ;;
esac
echo "$COMMAND"
$COMMAND
if [ $? != 0 ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
error "Building '$TARGET' failed."
exit 1
fi
done
}
make_md5sum() {
local FILE LOCAL_FILENAMES
if [ "$source" ]; then
for FILE in ${source[@]}; do
LOCAL_FILENAMES="$LOCAL_FILENAMES `get_filename $FILE`"
done
md5sum $LOCAL_FILENAMES | sed -e 's| .*/| |' | sort -k 2
fi
}
make_footprint() {
pkginfo --footprint $TARGET | \
sed "s|\tlib/modules/`uname -r`/|\tlib/modules/<kernel-version>/|g" | \
sort -k 3
}
check_md5sum() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $PKGMK_MD5SUM ]; then
make_md5sum > $FILE.md5sum
sort -k 2 $PKGMK_MD5SUM > $FILE.md5sum.orig
diff -w -t -U 0 $FILE.md5sum.orig $FILE.md5sum | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.md5sum.diff
if [ -s $FILE.md5sum.diff ]; then
error "Md5sum mismatch found:"
cat $FILE.md5sum.diff >&2
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
error "Md5sum not ok."
exit 1
fi
error "Building '$TARGET' failed."
exit 1
fi
else
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum not found."
exit 1
fi
warning "Md5sum not found, creating new."
make_md5sum > $PKGMK_MD5SUM
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum ok."
exit 0
fi
}
strip_files() {
local FILE FILTER
cd $PKG
if [ -f $PKGMK_ROOT/$PKGMK_NOSTRIP ]; then
FILTER="grep -v -f $PKGMK_ROOT/$PKGMK_NOSTRIP"
else
FILTER="cat"
fi
find . -type f -printf "%P\n" | $FILTER | while read FILE; do
case $(file -b "$FILE") in
*ELF*executable*not\ stripped)
strip --strip-all "$FILE"
;;
*ELF*shared\ object*not\ stripped)
strip --strip-unneeded "$FILE"
;;
current\ ar\ archive)
strip --strip-debug "$FILE"
esac
done
}
compress_manpages() {
local FILE DIR TARGET
cd $PKG
find . -type f -path "*/man/man*/*" | while read FILE; do
if [ "$FILE" = "${FILE%%.gz}" ]; then
gzip -9 "$FILE"
fi
done
find . -type l -path "*/man/man*/*" | while read FILE; do
TARGET=`readlink -n "$FILE"`
TARGET="${TARGET##*/}"
TARGET="${TARGET%%.gz}.gz"
rm -f "$FILE"
FILE="${FILE%%.gz}.gz"
DIR=`dirname "$FILE"`
if [ -e "$DIR/$TARGET" ]; then
ln -sf "$TARGET" "$FILE"
fi
done
}
check_footprint() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $TARGET ]; then
make_footprint > $FILE.footprint
if [ -f $PKGMK_FOOTPRINT ]; then
sort -k 3 $PKGMK_FOOTPRINT > $FILE.footprint.orig
diff -w -t -U 0 $FILE.footprint.orig $FILE.footprint | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.footprint.diff
if [ -s $FILE.footprint.diff ]; then
error "Footprint mismatch found:"
cat $FILE.footprint.diff >&2
BUILD_SUCCESSFUL="no"
fi
else
warning "Footprint not found, creating new."
mv $FILE.footprint $PKGMK_FOOTPRINT
fi
else
error "Package '$TARGET' was not found."
BUILD_SUCCESSFUL="no"
fi
}
make_work_dir() {
export PKG="$PKGMK_WORK_DIR/pkg"
export SRC="$PKGMK_WORK_DIR/src"
umask 022
cd $PKGMK_ROOT
remove_work_dir
mkdir -p $SRC $PKG
if [ "$PKGMK_IGNORE_MD5SUM" = "no" ]; then
check_md5sum
fi
}
remove_work_dir() {
rm -rf $PKGMK_WORK_DIR
}
build_package() {
local BUILD_SUCCESSFUL="no"
make_work_dir
if [ "$UID" != "0" ]; then
warning "Packages should be built as root."
fi
info "Building '$TARGET'."
unpack_source
cd $SRC
(set -e -x ; build)
if [ $? = 0 ]; then
if [ "$PKGMK_NO_STRIP" = "no" ]; then
strip_files
fi
compress_manpages
cd $PKG
info "Build result:"
tar czvvf $TARGET *
if [ $? = 0 ]; then
BUILD_SUCCESSFUL="yes"
if [ "$PKGMK_IGNORE_FOOTPRINT" = "yes" ]; then
warning "Footprint ignored."
else
check_footprint
fi
fi
fi
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
remove_work_dir
fi
if [ "$BUILD_SUCCESSFUL" = "yes" ]; then
info "Building '$TARGET' succeeded."
else
if [ -f $TARGET ]; then
touch -r $PKGMK_ROOT/$PKGMK_PKGFILE $TARGET &> /dev/null
fi
error "Building '$TARGET' failed."
exit 1
fi
}
install_package() {
local COMMAND
info "Installing '$TARGET'."
if [ "$PKGMK_INSTALL" = "install" ]; then
COMMAND="pkgadd $TARGET"
else
COMMAND="pkgadd -u $TARGET"
fi
cd $PKGMK_ROOT
echo "$COMMAND"
$COMMAND
if [ $? = 0 ]; then
info "Installing '$TARGET' succeeded."
else
error "Installing '$TARGET' failed."
exit 1
fi
}
recursive() {
local ARGS FILE DIR
ARGS=`echo "$@" | sed -e "s/--recursive//g" -e "s/-r//g"`
for FILE in `find $PKGMK_ROOT -name $PKGMK_PKGFILE | sort`; do
DIR="`dirname $FILE`/"
if [ -d $DIR ]; then
info "Entering directory '$DIR'."
(cd $DIR && $PKGMK_COMMAND $ARGS)
info "Leaving directory '$DIR'."
fi
done
}
clean() {
local FILE LOCAL_FILENAME
if [ -f $TARGET ]; then
info "Removing $TARGET"
rm -f $TARGET
fi
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ -e $LOCAL_FILENAME ] && [ "$LOCAL_FILENAME" != "$FILE" ]; then
info "Removing $LOCAL_FILENAME"
rm -f $LOCAL_FILENAME
fi
done
}
update_footprint() {
if [ ! -f $TARGET ]; then
error "Unable to update footprint. File '$TARGET' not found."
exit 1
fi
make_footprint > $PKGMK_FOOTPRINT
touch $TARGET
info "Footprint updated."
}
build_needed() {
local FILE RESULT
RESULT="yes"
if [ -f $TARGET ]; then
RESULT="no"
for FILE in $PKGMK_PKGFILE ${source[@]}; do
FILE=`get_filename $FILE`
if [ ! -e $FILE ] || [ ! $TARGET -nt $FILE ]; then
RESULT="yes"
break
fi
done
fi
echo $RESULT
}
interrupted() {
echo ""
error "Interrupted."
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
exit 1
}
print_help() {
echo "usage: `basename $PKGMK_COMMAND` [options]"
echo "options:"
echo " -i, --install build and install package"
echo " -u, --upgrade build and install package (as upgrade)"
echo " -r, --recursive search for and build packages recursively"
echo " -d, --download download missing source file(s)"
echo " -do, --download-only do not build, only download missing source file(s)"
echo " -eo, --extract-only do not build, only extract source file(s)"
echo " -utd, --up-to-date do not build, only check if package is up to date"
echo " -uf, --update-footprint update footprint using result from last build"
echo " -if, --ignore-footprint build package without checking footprint"
echo " -um, --update-md5sum update md5sum"
echo " -im, --ignore-md5sum build package without checking md5sum"
echo " -cm, --check-md5sum do not build, only check md5sum"
echo " -ns, --no-strip do not strip executable binaries or libraries"
echo " -f, --force build package even if it appears to be up to date"
echo " -c, --clean remove package and downloaded files"
echo " -kw, --keep-work keep temporary working directory"
echo " -cf, --config-file <file> use alternative configuration file"
echo " -v, --version print version and exit "
echo " -h, --help print help and exit"
}
parse_options() {
while [ "$1" ]; do
case $1 in
-i|--install)
PKGMK_INSTALL="install" ;;
-u|--upgrade)
PKGMK_INSTALL="upgrade" ;;
-r|--recursive)
PKGMK_RECURSIVE="yes" ;;
-d|--download)
PKGMK_DOWNLOAD="yes" ;;
-do|--download-only)
PKGMK_DOWNLOAD="yes"
PKGMK_DOWNLOAD_ONLY="yes" ;;
-eo|--extract-only)
PKGMK_EXTRACT_ONLY="yes" ;;
-utd|--up-to-date)
PKGMK_UP_TO_DATE="yes" ;;
-uf|--update-footprint)
PKGMK_UPDATE_FOOTPRINT="yes" ;;
-if|--ignore-footprint)
PKGMK_IGNORE_FOOTPRINT="yes" ;;
-um|--update-md5sum)
PKGMK_UPDATE_MD5SUM="yes" ;;
-im|--ignore-md5sum)
PKGMK_IGNORE_MD5SUM="yes" ;;
-cm|--check-md5sum)
PKGMK_CHECK_MD5SUM="yes" ;;
-ns|--no-strip)
PKGMK_NO_STRIP="yes" ;;
|
nipuL/pkgutils | 51c534c2bd638d6ef849bac15c6106a17a682b56 | Bug #347: wget options are configurable now. | diff --git a/pkgmk.conf b/pkgmk.conf
index 5d76a6a..07b1cbd 100644
--- a/pkgmk.conf
+++ b/pkgmk.conf
@@ -1,16 +1,17 @@
#
# /etc/pkgmk.conf: pkgmk(8) configuration
#
export CFLAGS="-O2 -march=i686 -pipe"
export CXXFLAGS="-O2 -march=i686 -pipe"
# PKGMK_SOURCE_MIRRORS=()
# PKGMK_SOURCE_DIR="$PWD"
# PKGMK_PACKAGE_DIR="$PWD"
# PKGMK_WORK_DIR="$PWD/work"
# PKGMK_DOWNLOAD="no"
# PKGMK_IGNORE_FOOTPRINT="no"
# PKGMK_NO_STRIP="no"
+# PKGMK_WGET_OPTS=""
# End of file
diff --git a/pkgmk.conf.5.in b/pkgmk.conf.5.in
index 36a26c1..dcb6a20 100644
--- a/pkgmk.conf.5.in
+++ b/pkgmk.conf.5.in
@@ -1,61 +1,65 @@
.TH pkgmk.conf 5 "" "pkgutils #VERSION#" ""
.SH NAME
\fBpkgmk.conf\fP \- Configuration file for pkgmk.
.SH DESCRIPTION
\fBpkgmk.conf\fP configures pkgutils package make, pkgmk(8).
.SH FILE FORMAT
The file consists of a number of variable assignments of the form \fBoption\fP=\fBvalue\fP. Comments can be specified by putting a hash (#) symbol as the first character on the line.
.SH DIRECTIVES
.LP
If some option is not used (commented out or not included in the configuration file at all) pkgmk will take a default action.
.TP
\fBexport CFLAGS='STRING'\fP
Set C compiler options.
.br
Default: none
.TP
\fBexport CXXFLAGS='STRING'\fP
Set C++ compiler options.
.br
Default: none
.TP
\fBPKGMK_SOURCE_MIRRORS=('STRING')\fP
Set mirrors to check and download source archives from.
.br
Default: none
.TP
\fBPKGMK_SOURCE_DIR='STRING'\fP
Set directory for downloaded source archives.
.br
Default: directory of Pkgfile.
.TP
\fBPKGMK_PACKAGE_DIR='STRING'\fR
Set directory for built packages.
.br
Default: directory of Pkgfile.
.TP
\fBPKGMK_WORK_DIR='STRING'\fP
Set directory for building packages.
.br
Default: '\fBfoo\fP/work', where \fBfoo\fP is the directory of the Pkgfile.
.TP
+\fBPKGMK_WGET_OPTS='STRING'\fP
+Additional options for wget(1), which is used by pkgmk to download all files.
+.br
+.TP
\fBPKGMK_DOWNLOAD='STRING'\fP
If set to 'yes', pkgmk will download the source archives if necessary.
.br
Default: 'no'
.TP
\fBPKGMK_IGNORE_FOOTPRINT='STRING'\fP
If set to 'yes', pkgmk will not perform a footprint check of the built package.
.br
Default: 'no'
.TP
\fBPKGMK_NO_STRIP='STRING'\fP
If set to 'no', pkgmk will strip built binaries.
.br
Default: 'no'
.SH SEE ALSO
pkgmk(8)
.SH COPYRIGHT
-pkgmk (pkgutils) is Copyright (c) 2000-2005 Per Liden and Copyright (c) 2006-2007 CRUX team (http://crux.nu).
+pkgmk (pkgutils) is Copyright (c) 2000-2005 Per Liden and Copyright (c) 2006-2008 CRUX team (http://crux.nu).
pkgmk (pkgutils) is licensed through the GNU General Public License.
Read the COPYING file for the complete license.
diff --git a/pkgmk.in b/pkgmk.in
index 1cc40d6..00d8e95 100755
--- a/pkgmk.in
+++ b/pkgmk.in
@@ -1,625 +1,625 @@
#!/bin/bash
#
# pkgutils
#
# Copyright (c) 2000-2005 Per Liden
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
info() {
echo "=======> $1"
}
warning() {
info "WARNING: $1" >&2
}
error() {
info "ERROR: $1" >&2
}
get_filename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
if [ "$FILE" != "$1" ]; then
FILE="$PKGMK_SOURCE_DIR/$FILE"
fi
echo $FILE
}
get_basename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
echo $FILE
}
check_pkgfile() {
if [ ! "$name" ]; then
error "Variable 'name' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$version" ]; then
error "Variable 'version' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$release" ]; then
error "Variable 'release' not specified in $PKGMK_PKGFILE."
exit 1
elif [ "`type -t build`" != "function" ]; then
error "Function 'build' not specified in $PKGMK_PKGFILE."
exit 1
fi
}
check_directory() {
if [ ! -d $1 ]; then
error "Directory '$1' does not exist."
exit 1
elif [ ! -w $1 ]; then
error "Directory '$1' not writable."
exit 1
elif [ ! -x $1 ] || [ ! -r $1 ]; then
error "Directory '$1' not readable."
exit 1
fi
}
download_file() {
info "Downloading '$1'."
if [ ! "`type -p wget`" ]; then
error "Command 'wget' not found."
exit 1
fi
LOCAL_FILENAME=`get_filename $1`
LOCAL_FILENAME_PARTIAL="$LOCAL_FILENAME.partial"
DOWNLOAD_OPTS="--passive-ftp --no-directories --tries=3 --waitretry=3 \
--directory-prefix=$PKGMK_SOURCE_DIR \
--output-document=$LOCAL_FILENAME_PARTIAL --no-check-certificate"
if [ -f "$LOCAL_FILENAME_PARTIAL" ]; then
info "Partial download found, trying to resume"
RESUME_CMD="-c"
fi
error=1
BASENAME=`get_basename $1`
for REPO in ${PKGMK_SOURCE_MIRRORS[@]}; do
REPO="`echo $REPO | sed 's|/$||'`"
- wget $RESUME_CMD $DOWNLOAD_OPTS $REPO/$BASENAME
+ wget $RESUME_CMD $DOWNLOAD_OPTS $PKGMK_WGET_OPTS $REPO/$BASENAME
error=$?
if [ $error == 0 ]; then
break
fi
done
if [ $error != 0 ]; then
while true; do
- wget $RESUME_CMD $DOWNLOAD_OPTS $1
+ wget $RESUME_CMD $DOWNLOAD_OPTS $PKGMK_WGET_OPTS $1
error=$?
if [ $error != 0 ] && [ "$RESUME_CMD" ]; then
info "Partial download failed, restarting"
rm -f "$LOCAL_FILENAME_PARTIAL"
RESUME_CMD=""
else
break
fi
done
fi
if [ $error != 0 ]; then
error "Downloading '$1' failed."
exit 1
fi
mv -f "$LOCAL_FILENAME_PARTIAL" "$LOCAL_FILENAME"
}
download_source() {
local FILE LOCAL_FILENAME
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ ! -e $LOCAL_FILENAME ]; then
if [ "$LOCAL_FILENAME" = "$FILE" ]; then
error "Source file '$LOCAL_FILENAME' not found (can not be downloaded, URL not specified)."
exit 1
else
if [ "$PKGMK_DOWNLOAD" = "yes" ]; then
download_file $FILE
else
error "Source file '$LOCAL_FILENAME' not found (use option -d to download)."
exit 1
fi
fi
fi
done
}
unpack_source() {
local FILE LOCAL_FILENAME COMMAND
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
case $LOCAL_FILENAME in
*.tar.gz|*.tar.Z|*.tgz)
COMMAND="tar -C $SRC --use-compress-program=gzip -xf $LOCAL_FILENAME" ;;
*.tar.bz2)
COMMAND="tar -C $SRC --use-compress-program=bzip2 -xf $LOCAL_FILENAME" ;;
*.zip)
COMMAND="unzip -qq -o -d $SRC $LOCAL_FILENAME" ;;
*)
COMMAND="cp $LOCAL_FILENAME $SRC" ;;
esac
echo "$COMMAND"
$COMMAND
if [ $? != 0 ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
error "Building '$TARGET' failed."
exit 1
fi
done
}
make_md5sum() {
local FILE LOCAL_FILENAMES
if [ "$source" ]; then
for FILE in ${source[@]}; do
LOCAL_FILENAMES="$LOCAL_FILENAMES `get_filename $FILE`"
done
md5sum $LOCAL_FILENAMES | sed -e 's| .*/| |' | sort -k 2
fi
}
make_footprint() {
pkginfo --footprint $TARGET | \
sed "s|\tlib/modules/`uname -r`/|\tlib/modules/<kernel-version>/|g" | \
sort -k 3
}
check_md5sum() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $PKGMK_MD5SUM ]; then
make_md5sum > $FILE.md5sum
sort -k 2 $PKGMK_MD5SUM > $FILE.md5sum.orig
diff -w -t -U 0 $FILE.md5sum.orig $FILE.md5sum | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.md5sum.diff
if [ -s $FILE.md5sum.diff ]; then
error "Md5sum mismatch found:"
cat $FILE.md5sum.diff >&2
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
error "Md5sum not ok."
exit 1
fi
error "Building '$TARGET' failed."
exit 1
fi
else
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum not found."
exit 1
fi
warning "Md5sum not found, creating new."
make_md5sum > $PKGMK_MD5SUM
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum ok."
exit 0
fi
}
strip_files() {
local FILE FILTER
cd $PKG
if [ -f $PKGMK_ROOT/$PKGMK_NOSTRIP ]; then
FILTER="grep -v -f $PKGMK_ROOT/$PKGMK_NOSTRIP"
else
FILTER="cat"
fi
find . -type f -printf "%P\n" | $FILTER | while read FILE; do
case $(file -b "$FILE") in
*ELF*executable*not\ stripped)
strip --strip-all "$FILE"
;;
*ELF*shared\ object*not\ stripped)
strip --strip-unneeded "$FILE"
;;
current\ ar\ archive)
strip --strip-debug "$FILE"
esac
done
}
compress_manpages() {
local FILE DIR TARGET
cd $PKG
find . -type f -path "*/man/man*/*" | while read FILE; do
if [ "$FILE" = "${FILE%%.gz}" ]; then
gzip -9 "$FILE"
fi
done
find . -type l -path "*/man/man*/*" | while read FILE; do
TARGET=`readlink -n "$FILE"`
TARGET="${TARGET##*/}"
TARGET="${TARGET%%.gz}.gz"
rm -f "$FILE"
FILE="${FILE%%.gz}.gz"
DIR=`dirname "$FILE"`
if [ -e "$DIR/$TARGET" ]; then
ln -sf "$TARGET" "$FILE"
fi
done
}
check_footprint() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $TARGET ]; then
make_footprint > $FILE.footprint
if [ -f $PKGMK_FOOTPRINT ]; then
sort -k 3 $PKGMK_FOOTPRINT > $FILE.footprint.orig
diff -w -t -U 0 $FILE.footprint.orig $FILE.footprint | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.footprint.diff
if [ -s $FILE.footprint.diff ]; then
error "Footprint mismatch found:"
cat $FILE.footprint.diff >&2
BUILD_SUCCESSFUL="no"
fi
else
warning "Footprint not found, creating new."
mv $FILE.footprint $PKGMK_FOOTPRINT
fi
else
error "Package '$TARGET' was not found."
BUILD_SUCCESSFUL="no"
fi
}
make_work_dir() {
export PKG="$PKGMK_WORK_DIR/pkg"
export SRC="$PKGMK_WORK_DIR/src"
umask 022
cd $PKGMK_ROOT
remove_work_dir
mkdir -p $SRC $PKG
if [ "$PKGMK_IGNORE_MD5SUM" = "no" ]; then
check_md5sum
fi
}
remove_work_dir() {
rm -rf $PKGMK_WORK_DIR
}
build_package() {
local BUILD_SUCCESSFUL="no"
make_work_dir
if [ "$UID" != "0" ]; then
warning "Packages should be built as root."
fi
info "Building '$TARGET'."
unpack_source
cd $SRC
(set -e -x ; build)
if [ $? = 0 ]; then
if [ "$PKGMK_NO_STRIP" = "no" ]; then
strip_files
fi
compress_manpages
cd $PKG
info "Build result:"
tar czvvf $TARGET *
if [ $? = 0 ]; then
BUILD_SUCCESSFUL="yes"
if [ "$PKGMK_IGNORE_FOOTPRINT" = "yes" ]; then
warning "Footprint ignored."
else
check_footprint
fi
fi
fi
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
remove_work_dir
fi
if [ "$BUILD_SUCCESSFUL" = "yes" ]; then
info "Building '$TARGET' succeeded."
else
if [ -f $TARGET ]; then
touch -r $PKGMK_ROOT/$PKGMK_PKGFILE $TARGET &> /dev/null
fi
error "Building '$TARGET' failed."
exit 1
fi
}
install_package() {
local COMMAND
info "Installing '$TARGET'."
if [ "$PKGMK_INSTALL" = "install" ]; then
COMMAND="pkgadd $TARGET"
else
COMMAND="pkgadd -u $TARGET"
fi
cd $PKGMK_ROOT
echo "$COMMAND"
$COMMAND
if [ $? = 0 ]; then
info "Installing '$TARGET' succeeded."
else
error "Installing '$TARGET' failed."
exit 1
fi
}
recursive() {
local ARGS FILE DIR
ARGS=`echo "$@" | sed -e "s/--recursive//g" -e "s/-r//g"`
for FILE in `find $PKGMK_ROOT -name $PKGMK_PKGFILE | sort`; do
DIR="`dirname $FILE`/"
if [ -d $DIR ]; then
info "Entering directory '$DIR'."
(cd $DIR && $PKGMK_COMMAND $ARGS)
info "Leaving directory '$DIR'."
fi
done
}
clean() {
local FILE LOCAL_FILENAME
if [ -f $TARGET ]; then
info "Removing $TARGET"
rm -f $TARGET
fi
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ -e $LOCAL_FILENAME ] && [ "$LOCAL_FILENAME" != "$FILE" ]; then
info "Removing $LOCAL_FILENAME"
rm -f $LOCAL_FILENAME
fi
done
}
update_footprint() {
if [ ! -f $TARGET ]; then
error "Unable to update footprint. File '$TARGET' not found."
exit 1
fi
make_footprint > $PKGMK_FOOTPRINT
touch $TARGET
info "Footprint updated."
}
build_needed() {
local FILE RESULT
RESULT="yes"
if [ -f $TARGET ]; then
RESULT="no"
for FILE in $PKGMK_PKGFILE ${source[@]}; do
FILE=`get_filename $FILE`
if [ ! -e $FILE ] || [ ! $TARGET -nt $FILE ]; then
RESULT="yes"
break
fi
done
fi
echo $RESULT
}
interrupted() {
echo ""
error "Interrupted."
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
exit 1
}
print_help() {
echo "usage: `basename $PKGMK_COMMAND` [options]"
echo "options:"
echo " -i, --install build and install package"
echo " -u, --upgrade build and install package (as upgrade)"
echo " -r, --recursive search for and build packages recursively"
echo " -d, --download download missing source file(s)"
echo " -do, --download-only do not build, only download missing source file(s)"
echo " -eo, --extract-only do not build, only extract source file(s)"
echo " -utd, --up-to-date do not build, only check if package is up to date"
echo " -uf, --update-footprint update footprint using result from last build"
echo " -if, --ignore-footprint build package without checking footprint"
echo " -um, --update-md5sum update md5sum"
echo " -im, --ignore-md5sum build package without checking md5sum"
echo " -cm, --check-md5sum do not build, only check md5sum"
echo " -ns, --no-strip do not strip executable binaries or libraries"
echo " -f, --force build package even if it appears to be up to date"
echo " -c, --clean remove package and downloaded files"
echo " -kw, --keep-work keep temporary working directory"
echo " -cf, --config-file <file> use alternative configuration file"
echo " -v, --version print version and exit "
echo " -h, --help print help and exit"
}
parse_options() {
while [ "$1" ]; do
case $1 in
-i|--install)
PKGMK_INSTALL="install" ;;
-u|--upgrade)
PKGMK_INSTALL="upgrade" ;;
-r|--recursive)
PKGMK_RECURSIVE="yes" ;;
-d|--download)
PKGMK_DOWNLOAD="yes" ;;
-do|--download-only)
PKGMK_DOWNLOAD="yes"
PKGMK_DOWNLOAD_ONLY="yes" ;;
-eo|--extract-only)
PKGMK_EXTRACT_ONLY="yes" ;;
-utd|--up-to-date)
PKGMK_UP_TO_DATE="yes" ;;
-uf|--update-footprint)
PKGMK_UPDATE_FOOTPRINT="yes" ;;
-if|--ignore-footprint)
PKGMK_IGNORE_FOOTPRINT="yes" ;;
-um|--update-md5sum)
PKGMK_UPDATE_MD5SUM="yes" ;;
-im|--ignore-md5sum)
PKGMK_IGNORE_MD5SUM="yes" ;;
-cm|--check-md5sum)
PKGMK_CHECK_MD5SUM="yes" ;;
-ns|--no-strip)
PKGMK_NO_STRIP="yes" ;;
-f|--force)
PKGMK_FORCE="yes" ;;
-c|--clean)
PKGMK_CLEAN="yes" ;;
-kw|--keep-work)
PKGMK_KEEP_WORK="yes" ;;
-cf|--config-file)
if [ ! "$2" ]; then
echo "`basename $PKGMK_COMMAND`: option $1 requires an argument"
exit 1
fi
PKGMK_CONFFILE="$2"
shift ;;
-v|--version)
echo "`basename $PKGMK_COMMAND` (pkgutils) $PKGMK_VERSION"
exit 0 ;;
-h|--help)
print_help
exit 0 ;;
*)
echo "`basename $PKGMK_COMMAND`: invalid option $1"
exit 1 ;;
esac
shift
done
}
main() {
local FILE TARGET
parse_options "$@"
if [ "$PKGMK_RECURSIVE" = "yes" ]; then
recursive "$@"
exit 0
fi
for FILE in $PKGMK_PKGFILE $PKGMK_CONFFILE; do
if [ ! -f $FILE ]; then
error "File '$FILE' not found."
exit 1
fi
. $FILE
done
check_directory "$PKGMK_SOURCE_DIR"
check_directory "$PKGMK_PACKAGE_DIR"
check_directory "`dirname $PKGMK_WORK_DIR`"
check_pkgfile
TARGET="$PKGMK_PACKAGE_DIR/$name#$version-$release.pkg.tar.gz"
if [ "$PKGMK_CLEAN" = "yes" ]; then
clean
exit 0
fi
if [ "$PKGMK_UPDATE_FOOTPRINT" = "yes" ]; then
update_footprint
exit 0
fi
if [ "$PKGMK_UPDATE_MD5SUM" = "yes" ]; then
download_source
make_md5sum > $PKGMK_MD5SUM
info "Md5sum updated."
exit 0
fi
|
nipuL/pkgutils | 92dbaab6a7ea34dc55308d12578453ec7e498295 | pkgmk: add "extract only" functionality, previously suggested by Lucas Hazel and Danny Rawlins | diff --git a/pkgmk.in b/pkgmk.in
index df50de8..1cc40d6 100755
--- a/pkgmk.in
+++ b/pkgmk.in
@@ -1,678 +1,699 @@
#!/bin/bash
#
# pkgutils
#
# Copyright (c) 2000-2005 Per Liden
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
info() {
echo "=======> $1"
}
warning() {
info "WARNING: $1" >&2
}
error() {
info "ERROR: $1" >&2
}
get_filename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
if [ "$FILE" != "$1" ]; then
FILE="$PKGMK_SOURCE_DIR/$FILE"
fi
echo $FILE
}
get_basename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
echo $FILE
}
check_pkgfile() {
if [ ! "$name" ]; then
error "Variable 'name' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$version" ]; then
error "Variable 'version' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$release" ]; then
error "Variable 'release' not specified in $PKGMK_PKGFILE."
exit 1
elif [ "`type -t build`" != "function" ]; then
error "Function 'build' not specified in $PKGMK_PKGFILE."
exit 1
fi
}
check_directory() {
if [ ! -d $1 ]; then
error "Directory '$1' does not exist."
exit 1
elif [ ! -w $1 ]; then
error "Directory '$1' not writable."
exit 1
elif [ ! -x $1 ] || [ ! -r $1 ]; then
error "Directory '$1' not readable."
exit 1
fi
}
download_file() {
info "Downloading '$1'."
if [ ! "`type -p wget`" ]; then
error "Command 'wget' not found."
exit 1
fi
LOCAL_FILENAME=`get_filename $1`
LOCAL_FILENAME_PARTIAL="$LOCAL_FILENAME.partial"
DOWNLOAD_OPTS="--passive-ftp --no-directories --tries=3 --waitretry=3 \
--directory-prefix=$PKGMK_SOURCE_DIR \
--output-document=$LOCAL_FILENAME_PARTIAL --no-check-certificate"
if [ -f "$LOCAL_FILENAME_PARTIAL" ]; then
info "Partial download found, trying to resume"
RESUME_CMD="-c"
fi
error=1
BASENAME=`get_basename $1`
for REPO in ${PKGMK_SOURCE_MIRRORS[@]}; do
REPO="`echo $REPO | sed 's|/$||'`"
wget $RESUME_CMD $DOWNLOAD_OPTS $REPO/$BASENAME
error=$?
if [ $error == 0 ]; then
break
fi
done
if [ $error != 0 ]; then
while true; do
wget $RESUME_CMD $DOWNLOAD_OPTS $1
error=$?
if [ $error != 0 ] && [ "$RESUME_CMD" ]; then
info "Partial download failed, restarting"
rm -f "$LOCAL_FILENAME_PARTIAL"
RESUME_CMD=""
else
break
fi
done
fi
if [ $error != 0 ]; then
error "Downloading '$1' failed."
exit 1
fi
mv -f "$LOCAL_FILENAME_PARTIAL" "$LOCAL_FILENAME"
}
download_source() {
local FILE LOCAL_FILENAME
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ ! -e $LOCAL_FILENAME ]; then
if [ "$LOCAL_FILENAME" = "$FILE" ]; then
error "Source file '$LOCAL_FILENAME' not found (can not be downloaded, URL not specified)."
exit 1
else
if [ "$PKGMK_DOWNLOAD" = "yes" ]; then
download_file $FILE
else
error "Source file '$LOCAL_FILENAME' not found (use option -d to download)."
exit 1
fi
fi
fi
done
}
unpack_source() {
local FILE LOCAL_FILENAME COMMAND
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
case $LOCAL_FILENAME in
*.tar.gz|*.tar.Z|*.tgz)
COMMAND="tar -C $SRC --use-compress-program=gzip -xf $LOCAL_FILENAME" ;;
*.tar.bz2)
COMMAND="tar -C $SRC --use-compress-program=bzip2 -xf $LOCAL_FILENAME" ;;
*.zip)
COMMAND="unzip -qq -o -d $SRC $LOCAL_FILENAME" ;;
*)
COMMAND="cp $LOCAL_FILENAME $SRC" ;;
esac
echo "$COMMAND"
$COMMAND
if [ $? != 0 ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
error "Building '$TARGET' failed."
exit 1
fi
done
}
make_md5sum() {
local FILE LOCAL_FILENAMES
if [ "$source" ]; then
for FILE in ${source[@]}; do
LOCAL_FILENAMES="$LOCAL_FILENAMES `get_filename $FILE`"
done
md5sum $LOCAL_FILENAMES | sed -e 's| .*/| |' | sort -k 2
fi
}
make_footprint() {
pkginfo --footprint $TARGET | \
sed "s|\tlib/modules/`uname -r`/|\tlib/modules/<kernel-version>/|g" | \
sort -k 3
}
check_md5sum() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $PKGMK_MD5SUM ]; then
make_md5sum > $FILE.md5sum
sort -k 2 $PKGMK_MD5SUM > $FILE.md5sum.orig
diff -w -t -U 0 $FILE.md5sum.orig $FILE.md5sum | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.md5sum.diff
if [ -s $FILE.md5sum.diff ]; then
error "Md5sum mismatch found:"
cat $FILE.md5sum.diff >&2
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
error "Md5sum not ok."
exit 1
fi
error "Building '$TARGET' failed."
exit 1
fi
else
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum not found."
exit 1
fi
warning "Md5sum not found, creating new."
make_md5sum > $PKGMK_MD5SUM
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum ok."
exit 0
fi
}
strip_files() {
local FILE FILTER
cd $PKG
if [ -f $PKGMK_ROOT/$PKGMK_NOSTRIP ]; then
FILTER="grep -v -f $PKGMK_ROOT/$PKGMK_NOSTRIP"
else
FILTER="cat"
fi
find . -type f -printf "%P\n" | $FILTER | while read FILE; do
case $(file -b "$FILE") in
*ELF*executable*not\ stripped)
strip --strip-all "$FILE"
;;
*ELF*shared\ object*not\ stripped)
strip --strip-unneeded "$FILE"
;;
current\ ar\ archive)
strip --strip-debug "$FILE"
esac
done
}
compress_manpages() {
local FILE DIR TARGET
cd $PKG
find . -type f -path "*/man/man*/*" | while read FILE; do
if [ "$FILE" = "${FILE%%.gz}" ]; then
gzip -9 "$FILE"
fi
done
find . -type l -path "*/man/man*/*" | while read FILE; do
TARGET=`readlink -n "$FILE"`
TARGET="${TARGET##*/}"
TARGET="${TARGET%%.gz}.gz"
rm -f "$FILE"
FILE="${FILE%%.gz}.gz"
DIR=`dirname "$FILE"`
if [ -e "$DIR/$TARGET" ]; then
ln -sf "$TARGET" "$FILE"
fi
done
}
check_footprint() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $TARGET ]; then
make_footprint > $FILE.footprint
if [ -f $PKGMK_FOOTPRINT ]; then
sort -k 3 $PKGMK_FOOTPRINT > $FILE.footprint.orig
diff -w -t -U 0 $FILE.footprint.orig $FILE.footprint | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.footprint.diff
if [ -s $FILE.footprint.diff ]; then
error "Footprint mismatch found:"
cat $FILE.footprint.diff >&2
BUILD_SUCCESSFUL="no"
fi
else
warning "Footprint not found, creating new."
mv $FILE.footprint $PKGMK_FOOTPRINT
fi
else
error "Package '$TARGET' was not found."
BUILD_SUCCESSFUL="no"
fi
}
-build_package() {
- local BUILD_SUCCESSFUL="no"
-
+make_work_dir() {
export PKG="$PKGMK_WORK_DIR/pkg"
export SRC="$PKGMK_WORK_DIR/src"
umask 022
cd $PKGMK_ROOT
- rm -rf $PKGMK_WORK_DIR
+ remove_work_dir
mkdir -p $SRC $PKG
-
+
if [ "$PKGMK_IGNORE_MD5SUM" = "no" ]; then
check_md5sum
fi
+}
+
+remove_work_dir() {
+ rm -rf $PKGMK_WORK_DIR
+}
+
+
+build_package() {
+ local BUILD_SUCCESSFUL="no"
+
+ make_work_dir
if [ "$UID" != "0" ]; then
warning "Packages should be built as root."
fi
info "Building '$TARGET'."
unpack_source
cd $SRC
(set -e -x ; build)
if [ $? = 0 ]; then
if [ "$PKGMK_NO_STRIP" = "no" ]; then
strip_files
fi
compress_manpages
cd $PKG
info "Build result:"
tar czvvf $TARGET *
if [ $? = 0 ]; then
BUILD_SUCCESSFUL="yes"
if [ "$PKGMK_IGNORE_FOOTPRINT" = "yes" ]; then
warning "Footprint ignored."
else
check_footprint
fi
fi
fi
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
- rm -rf $PKGMK_WORK_DIR
+ remove_work_dir
fi
if [ "$BUILD_SUCCESSFUL" = "yes" ]; then
info "Building '$TARGET' succeeded."
else
if [ -f $TARGET ]; then
touch -r $PKGMK_ROOT/$PKGMK_PKGFILE $TARGET &> /dev/null
fi
error "Building '$TARGET' failed."
exit 1
fi
}
install_package() {
local COMMAND
info "Installing '$TARGET'."
if [ "$PKGMK_INSTALL" = "install" ]; then
COMMAND="pkgadd $TARGET"
else
COMMAND="pkgadd -u $TARGET"
fi
cd $PKGMK_ROOT
echo "$COMMAND"
$COMMAND
if [ $? = 0 ]; then
info "Installing '$TARGET' succeeded."
else
error "Installing '$TARGET' failed."
exit 1
fi
}
recursive() {
local ARGS FILE DIR
ARGS=`echo "$@" | sed -e "s/--recursive//g" -e "s/-r//g"`
for FILE in `find $PKGMK_ROOT -name $PKGMK_PKGFILE | sort`; do
DIR="`dirname $FILE`/"
if [ -d $DIR ]; then
info "Entering directory '$DIR'."
(cd $DIR && $PKGMK_COMMAND $ARGS)
info "Leaving directory '$DIR'."
fi
done
}
clean() {
local FILE LOCAL_FILENAME
if [ -f $TARGET ]; then
info "Removing $TARGET"
rm -f $TARGET
fi
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ -e $LOCAL_FILENAME ] && [ "$LOCAL_FILENAME" != "$FILE" ]; then
info "Removing $LOCAL_FILENAME"
rm -f $LOCAL_FILENAME
fi
done
}
update_footprint() {
if [ ! -f $TARGET ]; then
error "Unable to update footprint. File '$TARGET' not found."
exit 1
fi
make_footprint > $PKGMK_FOOTPRINT
touch $TARGET
info "Footprint updated."
}
build_needed() {
local FILE RESULT
RESULT="yes"
if [ -f $TARGET ]; then
RESULT="no"
for FILE in $PKGMK_PKGFILE ${source[@]}; do
FILE=`get_filename $FILE`
if [ ! -e $FILE ] || [ ! $TARGET -nt $FILE ]; then
RESULT="yes"
break
fi
done
fi
echo $RESULT
}
interrupted() {
echo ""
error "Interrupted."
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
exit 1
}
print_help() {
echo "usage: `basename $PKGMK_COMMAND` [options]"
echo "options:"
echo " -i, --install build and install package"
echo " -u, --upgrade build and install package (as upgrade)"
echo " -r, --recursive search for and build packages recursively"
echo " -d, --download download missing source file(s)"
echo " -do, --download-only do not build, only download missing source file(s)"
+ echo " -eo, --extract-only do not build, only extract source file(s)"
echo " -utd, --up-to-date do not build, only check if package is up to date"
echo " -uf, --update-footprint update footprint using result from last build"
echo " -if, --ignore-footprint build package without checking footprint"
echo " -um, --update-md5sum update md5sum"
echo " -im, --ignore-md5sum build package without checking md5sum"
echo " -cm, --check-md5sum do not build, only check md5sum"
echo " -ns, --no-strip do not strip executable binaries or libraries"
echo " -f, --force build package even if it appears to be up to date"
echo " -c, --clean remove package and downloaded files"
echo " -kw, --keep-work keep temporary working directory"
echo " -cf, --config-file <file> use alternative configuration file"
echo " -v, --version print version and exit "
echo " -h, --help print help and exit"
}
parse_options() {
while [ "$1" ]; do
case $1 in
-i|--install)
PKGMK_INSTALL="install" ;;
-u|--upgrade)
PKGMK_INSTALL="upgrade" ;;
-r|--recursive)
PKGMK_RECURSIVE="yes" ;;
-d|--download)
PKGMK_DOWNLOAD="yes" ;;
-do|--download-only)
PKGMK_DOWNLOAD="yes"
PKGMK_DOWNLOAD_ONLY="yes" ;;
+ -eo|--extract-only)
+ PKGMK_EXTRACT_ONLY="yes" ;;
-utd|--up-to-date)
PKGMK_UP_TO_DATE="yes" ;;
-uf|--update-footprint)
PKGMK_UPDATE_FOOTPRINT="yes" ;;
-if|--ignore-footprint)
PKGMK_IGNORE_FOOTPRINT="yes" ;;
-um|--update-md5sum)
PKGMK_UPDATE_MD5SUM="yes" ;;
-im|--ignore-md5sum)
PKGMK_IGNORE_MD5SUM="yes" ;;
-cm|--check-md5sum)
PKGMK_CHECK_MD5SUM="yes" ;;
-ns|--no-strip)
PKGMK_NO_STRIP="yes" ;;
-f|--force)
PKGMK_FORCE="yes" ;;
-c|--clean)
PKGMK_CLEAN="yes" ;;
-kw|--keep-work)
PKGMK_KEEP_WORK="yes" ;;
-cf|--config-file)
if [ ! "$2" ]; then
echo "`basename $PKGMK_COMMAND`: option $1 requires an argument"
exit 1
fi
PKGMK_CONFFILE="$2"
shift ;;
-v|--version)
echo "`basename $PKGMK_COMMAND` (pkgutils) $PKGMK_VERSION"
exit 0 ;;
-h|--help)
print_help
exit 0 ;;
*)
echo "`basename $PKGMK_COMMAND`: invalid option $1"
exit 1 ;;
esac
shift
done
}
main() {
local FILE TARGET
parse_options "$@"
if [ "$PKGMK_RECURSIVE" = "yes" ]; then
recursive "$@"
exit 0
fi
for FILE in $PKGMK_PKGFILE $PKGMK_CONFFILE; do
if [ ! -f $FILE ]; then
error "File '$FILE' not found."
exit 1
fi
. $FILE
done
check_directory "$PKGMK_SOURCE_DIR"
check_directory "$PKGMK_PACKAGE_DIR"
check_directory "`dirname $PKGMK_WORK_DIR`"
check_pkgfile
TARGET="$PKGMK_PACKAGE_DIR/$name#$version-$release.pkg.tar.gz"
if [ "$PKGMK_CLEAN" = "yes" ]; then
clean
exit 0
fi
if [ "$PKGMK_UPDATE_FOOTPRINT" = "yes" ]; then
update_footprint
exit 0
fi
if [ "$PKGMK_UPDATE_MD5SUM" = "yes" ]; then
download_source
make_md5sum > $PKGMK_MD5SUM
info "Md5sum updated."
exit 0
fi
if [ "$PKGMK_DOWNLOAD_ONLY" = "yes" ]; then
download_source
exit 0
fi
+ if [ "$PKGMK_EXTRACT_ONLY" = "yes" ]; then
+ download_source
+ make_work_dir
+ info "Extracting sources of package '$name-$version'."
+ unpack_source
+ exit 0
+ fi
+
if [ "$PKGMK_UP_TO_DATE" = "yes" ]; then
if [ "`build_needed`" = "yes" ]; then
info "Package '$TARGET' is not up to date."
else
info "Package '$TARGET' is up to date."
fi
exit 0
fi
if [ "`build_needed`" = "no" ] && [ "$PKGMK_FORCE" = "no" ] && [ "$PKGMK_CHECK_MD5SUM" = "no" ]; then
info "Package '$TARGET' is up to date."
else
download_source
build_package
fi
if [ "$PKGMK_INSTALL" != "no" ]; then
install_package
fi
exit 0
}
trap "interrupted" SIGHUP SIGINT SIGQUIT SIGTERM
export LC_ALL=POSIX
readonly PKGMK_VERSION="#VERSION#"
readonly PKGMK_COMMAND="$0"
readonly PKGMK_ROOT="$PWD"
PKGMK_CONFFILE="/etc/pkgmk.conf"
PKGMK_PKGFILE="Pkgfile"
PKGMK_FOOTPRINT=".footprint"
PKGMK_MD5SUM=".md5sum"
PKGMK_NOSTRIP=".nostrip"
PKGMK_SOURCE_MIRRORS=()
PKGMK_SOURCE_DIR="$PWD"
PKGMK_PACKAGE_DIR="$PWD"
PKGMK_WORK_DIR="$PWD/work"
PKGMK_INSTALL="no"
PKGMK_RECURSIVE="no"
PKGMK_DOWNLOAD="no"
PKGMK_DOWNLOAD_ONLY="no"
+PKGMK_EXTRACT_ONLY="no"
PKGMK_UP_TO_DATE="no"
PKGMK_UPDATE_FOOTPRINT="no"
PKGMK_IGNORE_FOOTPRINT="no"
PKGMK_FORCE="no"
PKGMK_KEEP_WORK="no"
PKGMK_UPDATE_MD5SUM="no"
PKGMK_IGNORE_MD5SUM="no"
PKGMK_CHECK_MD5SUM="no"
PKGMK_NO_STRIP="no"
PKGMK_CLEAN="no"
main "$@"
# End of file
|
nipuL/pkgutils | 140951a0685c5b159a75f86ebaf8a8703a3568ac | Bug #287: Added a manpage for pkgmk.conf. | diff --git a/.gitignore b/.gitignore
index 0f6bd9c..e2c7965 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,8 @@
.depend
*.o
*.8
+*.5
pkgadd
pkgmk
rejmerge
diff --git a/Makefile b/Makefile
index 5e03b4c..0dd5406 100644
--- a/Makefile
+++ b/Makefile
@@ -1,100 +1,101 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
VERSION = 5.32.0
NAME = pkgutils-$(VERSION)
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDFLAGS += -static -larchive -lz -lbz2
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
-MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
+MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8 pkgmk.conf.5
all: pkgadd pkgmk rejmerge man
pkgadd: .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
rm -rf $(NAME) $(NAME).tar.gz
git archive --format=tar --prefix=$(NAME)/ HEAD | tar -x
git log > $(NAME)/ChangeLog
tar czvf $(NAME).tar.gz $(NAME)
rm -rf $(NAME)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
+ install -D -m0644 pkgmk.conf.5 $(DESTDIR)$(MANDIR)/man5/pkgmk.conf.5
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
# End of file
diff --git a/pkgmk.8.in b/pkgmk.8.in
index b131b18..b9fca26 100644
--- a/pkgmk.8.in
+++ b/pkgmk.8.in
@@ -1,93 +1,93 @@
.TH pkgmk 8 "" "pkgutils #VERSION#" ""
.SH NAME
pkgmk \- make software package
.SH SYNOPSIS
\fBpkgmk [options]\fP
.SH DESCRIPTION
\fBpkgmk\fP is a \fIpackage management\fP utility, which makes
a software package. A \fIpackage\fP is an archive of files (.pkg.tar.gz)
that can be installed using pkgadd(8).
To prepare to use pkgmk, you must write a file named \fIPkgfile\fP
that describes how the package should be build. Once a suitable
\fIPkgfile\fP file exists, each time you change some source files,
you simply execute pkgmk to bring the package up to date. The pkgmk
program uses the \fIPkgfile\fP file and the last-modification
times of the source files to decide if the package needs to be updated.
Global build configuration is stored in \fI/etc/pkgmk.conf\fP. This
file is read by pkgmk at startup.
.SH OPTIONS
.TP
.B "\-i, \-\-install"
Install package using pkgadd(8) after successful build.
.TP
.B "\-u, \-\-upgrade"
Install package as an upgrade using pkgadd(8) after successful build.
.TP
.B "\-r, \-\-recursive"
Search for and build packages recursively.
.TP
.B "\-d, \-\-download"
Download missing source file(s).
.TP
.B "\-do, \-\-download\-only"
Do not build, only download missing source file(s).
.TP
.B "\-utd, \-\-up\-to\-date"
Do not build, only check if the package is up to date.
.TP
.B "\-uf, \-\-update\-footprint"
Update footprint and treat last build as successful.
.TP
.B "\-if, \-\-ignore\-footprint"
Build package without checking footprint.
.TP
.B "\-um, \-\-update\-md5sum"
Update md5sum using the current source files.
.TP
.B "\-im, \-\-ignore\-md5sum"
Build package without checking md5sum first.
.TP
.B "\-ns, \-\-no\-strip"
Do not strip executable binaries or libraries.
.TP
.B "\-f, \-\-force"
Build package even if it appears to be up to date.
.TP
.B "\-c, \-\-clean"
Remove the (previously built) package and the downloaded source files.
.TP
.B "\-kw, \-\-keep-work"
Keep temporary working directory.
.TP
.B "\-cf, \-\-config\-file <file>"
Use alternative configuration file (default is /etc/pkgmk.conf).
.TP
.B "\-v, \-\-version"
Print version and exit.
.TP
.B "\-h, \-\-help"
Print help and exit.
.SH FILES
.TP
.B "Pkgfile"
Package build description.
.TP
.B ".footprint"
Package footprint (used for regression testing).
.TP
.B ".md5sum"
MD5 checksum of source files.
.TP
.B "/etc/pkgmk.conf"
Global package make configuration.
.TP
.B "wget"
Used by pkgmk to download source code.
.SH SEE ALSO
-pkgadd(8), pkgrm(8), pkginfo(8), rejmerge(8), wget(1)
+pkgmk.conf(5), pkgadd(8), pkgrm(8), pkginfo(8), rejmerge(8), wget(1)
.SH COPYRIGHT
pkgmk (pkgutils) is Copyright (c) 2000-2005 Per Liden and Copyright (c) 2006-2007 CRUX team (http://crux.nu).
pkgmk (pkgutils) is licensed through the GNU General Public License.
Read the COPYING file for the complete license.
diff --git a/pkgmk.conf.5.in b/pkgmk.conf.5.in
new file mode 100644
index 0000000..36a26c1
--- /dev/null
+++ b/pkgmk.conf.5.in
@@ -0,0 +1,61 @@
+.TH pkgmk.conf 5 "" "pkgutils #VERSION#" ""
+.SH NAME
+\fBpkgmk.conf\fP \- Configuration file for pkgmk.
+.SH DESCRIPTION
+\fBpkgmk.conf\fP configures pkgutils package make, pkgmk(8).
+.SH FILE FORMAT
+The file consists of a number of variable assignments of the form \fBoption\fP=\fBvalue\fP. Comments can be specified by putting a hash (#) symbol as the first character on the line.
+.SH DIRECTIVES
+.LP
+If some option is not used (commented out or not included in the configuration file at all) pkgmk will take a default action.
+.TP
+\fBexport CFLAGS='STRING'\fP
+Set C compiler options.
+.br
+Default: none
+.TP
+\fBexport CXXFLAGS='STRING'\fP
+Set C++ compiler options.
+.br
+Default: none
+.TP
+\fBPKGMK_SOURCE_MIRRORS=('STRING')\fP
+Set mirrors to check and download source archives from.
+.br
+Default: none
+.TP
+\fBPKGMK_SOURCE_DIR='STRING'\fP
+Set directory for downloaded source archives.
+.br
+Default: directory of Pkgfile.
+.TP
+\fBPKGMK_PACKAGE_DIR='STRING'\fR
+Set directory for built packages.
+.br
+Default: directory of Pkgfile.
+.TP
+\fBPKGMK_WORK_DIR='STRING'\fP
+Set directory for building packages.
+.br
+Default: '\fBfoo\fP/work', where \fBfoo\fP is the directory of the Pkgfile.
+.TP
+\fBPKGMK_DOWNLOAD='STRING'\fP
+If set to 'yes', pkgmk will download the source archives if necessary.
+.br
+Default: 'no'
+.TP
+\fBPKGMK_IGNORE_FOOTPRINT='STRING'\fP
+If set to 'yes', pkgmk will not perform a footprint check of the built package.
+.br
+Default: 'no'
+.TP
+\fBPKGMK_NO_STRIP='STRING'\fP
+If set to 'no', pkgmk will strip built binaries.
+.br
+Default: 'no'
+.SH SEE ALSO
+pkgmk(8)
+.SH COPYRIGHT
+pkgmk (pkgutils) is Copyright (c) 2000-2005 Per Liden and Copyright (c) 2006-2007 CRUX team (http://crux.nu).
+pkgmk (pkgutils) is licensed through the GNU General Public License.
+Read the COPYING file for the complete license.
|
nipuL/pkgutils | 765b5014db1cc1fd3278f0b425d586b6dce75ae1 | Bug #241: Don't check SSL certificates. | diff --git a/pkgmk.in b/pkgmk.in
index da9b303..df50de8 100755
--- a/pkgmk.in
+++ b/pkgmk.in
@@ -1,604 +1,604 @@
#!/bin/bash
#
# pkgutils
#
# Copyright (c) 2000-2005 Per Liden
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
info() {
echo "=======> $1"
}
warning() {
info "WARNING: $1" >&2
}
error() {
info "ERROR: $1" >&2
}
get_filename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
if [ "$FILE" != "$1" ]; then
FILE="$PKGMK_SOURCE_DIR/$FILE"
fi
echo $FILE
}
get_basename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
echo $FILE
}
check_pkgfile() {
if [ ! "$name" ]; then
error "Variable 'name' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$version" ]; then
error "Variable 'version' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$release" ]; then
error "Variable 'release' not specified in $PKGMK_PKGFILE."
exit 1
elif [ "`type -t build`" != "function" ]; then
error "Function 'build' not specified in $PKGMK_PKGFILE."
exit 1
fi
}
check_directory() {
if [ ! -d $1 ]; then
error "Directory '$1' does not exist."
exit 1
elif [ ! -w $1 ]; then
error "Directory '$1' not writable."
exit 1
elif [ ! -x $1 ] || [ ! -r $1 ]; then
error "Directory '$1' not readable."
exit 1
fi
}
download_file() {
info "Downloading '$1'."
if [ ! "`type -p wget`" ]; then
error "Command 'wget' not found."
exit 1
fi
LOCAL_FILENAME=`get_filename $1`
LOCAL_FILENAME_PARTIAL="$LOCAL_FILENAME.partial"
DOWNLOAD_OPTS="--passive-ftp --no-directories --tries=3 --waitretry=3 \
--directory-prefix=$PKGMK_SOURCE_DIR \
- --output-document=$LOCAL_FILENAME_PARTIAL"
+ --output-document=$LOCAL_FILENAME_PARTIAL --no-check-certificate"
if [ -f "$LOCAL_FILENAME_PARTIAL" ]; then
info "Partial download found, trying to resume"
RESUME_CMD="-c"
fi
error=1
BASENAME=`get_basename $1`
for REPO in ${PKGMK_SOURCE_MIRRORS[@]}; do
REPO="`echo $REPO | sed 's|/$||'`"
wget $RESUME_CMD $DOWNLOAD_OPTS $REPO/$BASENAME
error=$?
if [ $error == 0 ]; then
break
fi
done
if [ $error != 0 ]; then
while true; do
wget $RESUME_CMD $DOWNLOAD_OPTS $1
error=$?
if [ $error != 0 ] && [ "$RESUME_CMD" ]; then
info "Partial download failed, restarting"
rm -f "$LOCAL_FILENAME_PARTIAL"
RESUME_CMD=""
else
break
fi
done
fi
if [ $error != 0 ]; then
error "Downloading '$1' failed."
exit 1
fi
mv -f "$LOCAL_FILENAME_PARTIAL" "$LOCAL_FILENAME"
}
download_source() {
local FILE LOCAL_FILENAME
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ ! -e $LOCAL_FILENAME ]; then
if [ "$LOCAL_FILENAME" = "$FILE" ]; then
error "Source file '$LOCAL_FILENAME' not found (can not be downloaded, URL not specified)."
exit 1
else
if [ "$PKGMK_DOWNLOAD" = "yes" ]; then
download_file $FILE
else
error "Source file '$LOCAL_FILENAME' not found (use option -d to download)."
exit 1
fi
fi
fi
done
}
unpack_source() {
local FILE LOCAL_FILENAME COMMAND
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
case $LOCAL_FILENAME in
*.tar.gz|*.tar.Z|*.tgz)
COMMAND="tar -C $SRC --use-compress-program=gzip -xf $LOCAL_FILENAME" ;;
*.tar.bz2)
COMMAND="tar -C $SRC --use-compress-program=bzip2 -xf $LOCAL_FILENAME" ;;
*.zip)
COMMAND="unzip -qq -o -d $SRC $LOCAL_FILENAME" ;;
*)
COMMAND="cp $LOCAL_FILENAME $SRC" ;;
esac
echo "$COMMAND"
$COMMAND
if [ $? != 0 ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
error "Building '$TARGET' failed."
exit 1
fi
done
}
make_md5sum() {
local FILE LOCAL_FILENAMES
if [ "$source" ]; then
for FILE in ${source[@]}; do
LOCAL_FILENAMES="$LOCAL_FILENAMES `get_filename $FILE`"
done
md5sum $LOCAL_FILENAMES | sed -e 's| .*/| |' | sort -k 2
fi
}
make_footprint() {
pkginfo --footprint $TARGET | \
sed "s|\tlib/modules/`uname -r`/|\tlib/modules/<kernel-version>/|g" | \
sort -k 3
}
check_md5sum() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $PKGMK_MD5SUM ]; then
make_md5sum > $FILE.md5sum
sort -k 2 $PKGMK_MD5SUM > $FILE.md5sum.orig
diff -w -t -U 0 $FILE.md5sum.orig $FILE.md5sum | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.md5sum.diff
if [ -s $FILE.md5sum.diff ]; then
error "Md5sum mismatch found:"
cat $FILE.md5sum.diff >&2
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
error "Md5sum not ok."
exit 1
fi
error "Building '$TARGET' failed."
exit 1
fi
else
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum not found."
exit 1
fi
warning "Md5sum not found, creating new."
make_md5sum > $PKGMK_MD5SUM
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum ok."
exit 0
fi
}
strip_files() {
local FILE FILTER
cd $PKG
if [ -f $PKGMK_ROOT/$PKGMK_NOSTRIP ]; then
FILTER="grep -v -f $PKGMK_ROOT/$PKGMK_NOSTRIP"
else
FILTER="cat"
fi
find . -type f -printf "%P\n" | $FILTER | while read FILE; do
case $(file -b "$FILE") in
*ELF*executable*not\ stripped)
strip --strip-all "$FILE"
;;
*ELF*shared\ object*not\ stripped)
strip --strip-unneeded "$FILE"
;;
current\ ar\ archive)
strip --strip-debug "$FILE"
esac
done
}
compress_manpages() {
local FILE DIR TARGET
cd $PKG
find . -type f -path "*/man/man*/*" | while read FILE; do
if [ "$FILE" = "${FILE%%.gz}" ]; then
gzip -9 "$FILE"
fi
done
find . -type l -path "*/man/man*/*" | while read FILE; do
TARGET=`readlink -n "$FILE"`
TARGET="${TARGET##*/}"
TARGET="${TARGET%%.gz}.gz"
rm -f "$FILE"
FILE="${FILE%%.gz}.gz"
DIR=`dirname "$FILE"`
if [ -e "$DIR/$TARGET" ]; then
ln -sf "$TARGET" "$FILE"
fi
done
}
check_footprint() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $TARGET ]; then
make_footprint > $FILE.footprint
if [ -f $PKGMK_FOOTPRINT ]; then
sort -k 3 $PKGMK_FOOTPRINT > $FILE.footprint.orig
diff -w -t -U 0 $FILE.footprint.orig $FILE.footprint | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.footprint.diff
if [ -s $FILE.footprint.diff ]; then
error "Footprint mismatch found:"
cat $FILE.footprint.diff >&2
BUILD_SUCCESSFUL="no"
fi
else
warning "Footprint not found, creating new."
mv $FILE.footprint $PKGMK_FOOTPRINT
fi
else
error "Package '$TARGET' was not found."
BUILD_SUCCESSFUL="no"
fi
}
build_package() {
local BUILD_SUCCESSFUL="no"
export PKG="$PKGMK_WORK_DIR/pkg"
export SRC="$PKGMK_WORK_DIR/src"
umask 022
cd $PKGMK_ROOT
rm -rf $PKGMK_WORK_DIR
mkdir -p $SRC $PKG
if [ "$PKGMK_IGNORE_MD5SUM" = "no" ]; then
check_md5sum
fi
if [ "$UID" != "0" ]; then
warning "Packages should be built as root."
fi
info "Building '$TARGET'."
unpack_source
cd $SRC
(set -e -x ; build)
if [ $? = 0 ]; then
if [ "$PKGMK_NO_STRIP" = "no" ]; then
strip_files
fi
compress_manpages
cd $PKG
info "Build result:"
tar czvvf $TARGET *
if [ $? = 0 ]; then
BUILD_SUCCESSFUL="yes"
if [ "$PKGMK_IGNORE_FOOTPRINT" = "yes" ]; then
warning "Footprint ignored."
else
check_footprint
fi
fi
fi
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$BUILD_SUCCESSFUL" = "yes" ]; then
info "Building '$TARGET' succeeded."
else
if [ -f $TARGET ]; then
touch -r $PKGMK_ROOT/$PKGMK_PKGFILE $TARGET &> /dev/null
fi
error "Building '$TARGET' failed."
exit 1
fi
}
install_package() {
local COMMAND
info "Installing '$TARGET'."
if [ "$PKGMK_INSTALL" = "install" ]; then
COMMAND="pkgadd $TARGET"
else
COMMAND="pkgadd -u $TARGET"
fi
cd $PKGMK_ROOT
echo "$COMMAND"
$COMMAND
if [ $? = 0 ]; then
info "Installing '$TARGET' succeeded."
else
error "Installing '$TARGET' failed."
exit 1
fi
}
recursive() {
local ARGS FILE DIR
ARGS=`echo "$@" | sed -e "s/--recursive//g" -e "s/-r//g"`
for FILE in `find $PKGMK_ROOT -name $PKGMK_PKGFILE | sort`; do
DIR="`dirname $FILE`/"
if [ -d $DIR ]; then
info "Entering directory '$DIR'."
(cd $DIR && $PKGMK_COMMAND $ARGS)
info "Leaving directory '$DIR'."
fi
done
}
clean() {
local FILE LOCAL_FILENAME
if [ -f $TARGET ]; then
info "Removing $TARGET"
rm -f $TARGET
fi
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ -e $LOCAL_FILENAME ] && [ "$LOCAL_FILENAME" != "$FILE" ]; then
info "Removing $LOCAL_FILENAME"
rm -f $LOCAL_FILENAME
fi
done
}
update_footprint() {
if [ ! -f $TARGET ]; then
error "Unable to update footprint. File '$TARGET' not found."
exit 1
fi
make_footprint > $PKGMK_FOOTPRINT
touch $TARGET
info "Footprint updated."
}
build_needed() {
local FILE RESULT
RESULT="yes"
if [ -f $TARGET ]; then
RESULT="no"
for FILE in $PKGMK_PKGFILE ${source[@]}; do
FILE=`get_filename $FILE`
if [ ! -e $FILE ] || [ ! $TARGET -nt $FILE ]; then
RESULT="yes"
break
fi
done
fi
echo $RESULT
}
interrupted() {
echo ""
error "Interrupted."
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
exit 1
}
print_help() {
echo "usage: `basename $PKGMK_COMMAND` [options]"
echo "options:"
echo " -i, --install build and install package"
echo " -u, --upgrade build and install package (as upgrade)"
echo " -r, --recursive search for and build packages recursively"
echo " -d, --download download missing source file(s)"
echo " -do, --download-only do not build, only download missing source file(s)"
echo " -utd, --up-to-date do not build, only check if package is up to date"
echo " -uf, --update-footprint update footprint using result from last build"
echo " -if, --ignore-footprint build package without checking footprint"
echo " -um, --update-md5sum update md5sum"
echo " -im, --ignore-md5sum build package without checking md5sum"
echo " -cm, --check-md5sum do not build, only check md5sum"
echo " -ns, --no-strip do not strip executable binaries or libraries"
echo " -f, --force build package even if it appears to be up to date"
echo " -c, --clean remove package and downloaded files"
echo " -kw, --keep-work keep temporary working directory"
echo " -cf, --config-file <file> use alternative configuration file"
echo " -v, --version print version and exit "
echo " -h, --help print help and exit"
}
parse_options() {
while [ "$1" ]; do
case $1 in
-i|--install)
PKGMK_INSTALL="install" ;;
-u|--upgrade)
PKGMK_INSTALL="upgrade" ;;
-r|--recursive)
PKGMK_RECURSIVE="yes" ;;
-d|--download)
PKGMK_DOWNLOAD="yes" ;;
-do|--download-only)
PKGMK_DOWNLOAD="yes"
PKGMK_DOWNLOAD_ONLY="yes" ;;
-utd|--up-to-date)
PKGMK_UP_TO_DATE="yes" ;;
-uf|--update-footprint)
PKGMK_UPDATE_FOOTPRINT="yes" ;;
-if|--ignore-footprint)
PKGMK_IGNORE_FOOTPRINT="yes" ;;
-um|--update-md5sum)
PKGMK_UPDATE_MD5SUM="yes" ;;
-im|--ignore-md5sum)
PKGMK_IGNORE_MD5SUM="yes" ;;
-cm|--check-md5sum)
PKGMK_CHECK_MD5SUM="yes" ;;
-ns|--no-strip)
PKGMK_NO_STRIP="yes" ;;
-f|--force)
PKGMK_FORCE="yes" ;;
-c|--clean)
PKGMK_CLEAN="yes" ;;
-kw|--keep-work)
PKGMK_KEEP_WORK="yes" ;;
-cf|--config-file)
if [ ! "$2" ]; then
echo "`basename $PKGMK_COMMAND`: option $1 requires an argument"
exit 1
fi
PKGMK_CONFFILE="$2"
shift ;;
-v|--version)
echo "`basename $PKGMK_COMMAND` (pkgutils) $PKGMK_VERSION"
exit 0 ;;
-h|--help)
print_help
exit 0 ;;
*)
echo "`basename $PKGMK_COMMAND`: invalid option $1"
exit 1 ;;
esac
shift
done
}
main() {
local FILE TARGET
parse_options "$@"
if [ "$PKGMK_RECURSIVE" = "yes" ]; then
recursive "$@"
exit 0
fi
for FILE in $PKGMK_PKGFILE $PKGMK_CONFFILE; do
if [ ! -f $FILE ]; then
error "File '$FILE' not found."
exit 1
fi
. $FILE
done
check_directory "$PKGMK_SOURCE_DIR"
check_directory "$PKGMK_PACKAGE_DIR"
check_directory "`dirname $PKGMK_WORK_DIR`"
check_pkgfile
TARGET="$PKGMK_PACKAGE_DIR/$name#$version-$release.pkg.tar.gz"
if [ "$PKGMK_CLEAN" = "yes" ]; then
clean
exit 0
fi
if [ "$PKGMK_UPDATE_FOOTPRINT" = "yes" ]; then
update_footprint
exit 0
|
nipuL/pkgutils | 6ae354d751e69982f46acf37fa83cd0679eb68b7 | Bug #244: Relative paths are supported now in pkgadd -r. | diff --git a/pkgutil.cc b/pkgutil.cc
index 216ca53..709e748 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,811 +1,814 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
// Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
#define INIT_ARCHIVE(ar) \
archive_read_support_compression_all((ar)); \
archive_read_support_format_all((ar))
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
mode_t mode = archive_entry_mode(entry);
if (S_ISREG(mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
+ char buf[PATH_MAX];
+ string absroot;
archive = archive_read_new();
INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
+ absroot = getcwd(buf, sizeof(buf));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
- string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
- string original_filename = trim_filename(root + string("/") + archive_filename);
+ string reject_dir = trim_filename(absroot + string("/") + string(PKG_REJECTED));
+ string original_filename = trim_filename(absroot + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
mode_t mode;
cout << utilname << ": ignoring " << archive_filename << endl;
mode = archive_entry_mode(entry);
if (S_ISREG(mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
unsigned int flags = ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_UNLINK;
if (archive_read_extract(archive, entry, flags) != ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
mode_t mode = archive_entry_mode(entry);
// Directory
if (S_ISDIR(mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
map<string, mode_t> hardlink_target_modes;
// We first do a run over the archive and remember the modes
// of regular files.
// In the second run, we print the footprint - using the stored
// modes for hardlinks.
//
// FIXME the code duplication here is butt ugly
archive = archive_read_new();
INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
if (!archive_entry_hardlink(entry)) {
const char *s = archive_entry_pathname(entry);
hardlink_target_modes[s] = mode;
}
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
archive_read_finish(archive);
// Too bad, there doesn't seem to be a way to reuse our archive
// instance
archive = archive_read_new();
INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
// Access permissions
if (S_ISLNK(mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
const char *h = archive_entry_hardlink(entry);
if (h)
cout << mtos(hardlink_target_modes[h]);
else
cout << mtos(mode);
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(mode) ||
S_ISBLK(mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | c67507556d9eaa476ec142762f041fd9b254655d | Bumped version to 5.32.0. | diff --git a/Makefile b/Makefile
index 19279c6..5e03b4c 100644
--- a/Makefile
+++ b/Makefile
@@ -1,100 +1,100 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
-VERSION = 5.31.0
+VERSION = 5.32.0
NAME = pkgutils-$(VERSION)
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDFLAGS += -static -larchive -lz -lbz2
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
all: pkgadd pkgmk rejmerge man
pkgadd: .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
rm -rf $(NAME) $(NAME).tar.gz
git archive --format=tar --prefix=$(NAME)/ HEAD | tar -x
git log > $(NAME)/ChangeLog
tar czvf $(NAME).tar.gz $(NAME)
rm -rf $(NAME)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
# End of file
|
nipuL/pkgutils | 3c0fce38e98fa4d796c94bd301afd138e27ab40e | Removed /etc/mail/cf from the UPGRADE rules in pkgadd.conf. | diff --git a/pkgadd.conf b/pkgadd.conf
index ae18261..6af9cb8 100644
--- a/pkgadd.conf
+++ b/pkgadd.conf
@@ -1,26 +1,25 @@
#
# /etc/pkgadd.conf: pkgadd(8) configuration
#
# Default rule (implicit)
#UPGRADE ^.*$ YES
UPGRADE ^etc/.*$ NO
UPGRADE ^var/log/.*$ NO
UPGRADE ^var/spool/\w*cron/.*$ NO
UPGRADE ^var/run/utmp$ NO
-UPGRADE ^etc/mail/cf/.*$ YES
UPGRADE ^etc/ports/drivers/.*$ YES
UPGRADE ^etc/X11/.*$ YES
UPGRADE ^etc/rc.*$ YES
UPGRADE ^etc/rc\.local$ NO
UPGRADE ^etc/rc\.modules$ NO
UPGRADE ^etc/rc\.conf$ NO
UPGRADE ^etc/rc\.d/net$ NO
UPGRADE ^etc/udev/rules.d/.*$ YES
UPGRADE ^etc/udev/rules.d/1.*$ NO
# End of file
|
nipuL/pkgutils | d324dd089cd8d643a3d6616de11de178919e10e7 | Bug #204: Restore mtime for extracted files. | diff --git a/pkgutil.cc b/pkgutil.cc
index b3afa51..216ca53 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,811 +1,811 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
// Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
#define INIT_ARCHIVE(ar) \
archive_read_support_compression_all((ar)); \
archive_read_support_format_all((ar))
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
mode_t mode = archive_entry_mode(entry);
if (S_ISREG(mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
mode_t mode;
cout << utilname << ": ignoring " << archive_filename << endl;
mode = archive_entry_mode(entry);
if (S_ISREG(mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
- unsigned int flags = ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_UNLINK;
+ unsigned int flags = ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_UNLINK;
if (archive_read_extract(archive, entry, flags) != ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
mode_t mode = archive_entry_mode(entry);
// Directory
if (S_ISDIR(mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
map<string, mode_t> hardlink_target_modes;
// We first do a run over the archive and remember the modes
// of regular files.
// In the second run, we print the footprint - using the stored
// modes for hardlinks.
//
// FIXME the code duplication here is butt ugly
archive = archive_read_new();
INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
if (!archive_entry_hardlink(entry)) {
const char *s = archive_entry_pathname(entry);
hardlink_target_modes[s] = mode;
}
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
archive_read_finish(archive);
// Too bad, there doesn't seem to be a way to reuse our archive
// instance
archive = archive_read_new();
INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
// Access permissions
if (S_ISLNK(mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
const char *h = archive_entry_hardlink(entry);
if (h)
cout << mtos(hardlink_target_modes[h]);
else
cout << mtos(mode);
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(mode) ||
S_ISBLK(mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | 2d9e8fdf3f58dc8a0a5d0e198d2da32976b8b62c | Bumped version to 5.31.0. | diff --git a/Makefile b/Makefile
index 67c334c..19279c6 100644
--- a/Makefile
+++ b/Makefile
@@ -1,100 +1,100 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
-VERSION = 5.30.0
+VERSION = 5.31.0
NAME = pkgutils-$(VERSION)
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDFLAGS += -static -larchive -lz -lbz2
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
all: pkgadd pkgmk rejmerge man
pkgadd: .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
rm -rf $(NAME) $(NAME).tar.gz
git archive --format=tar --prefix=$(NAME)/ HEAD | tar -x
git log > $(NAME)/ChangeLog
tar czvf $(NAME).tar.gz $(NAME)
rm -rf $(NAME)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
# End of file
|
nipuL/pkgutils | 2dee8e17ce94c29744a8d097b2bf6b3165f52659 | added PKGMK_SOURCE_MIRRORS support | diff --git a/pkgmk.conf b/pkgmk.conf
index 6e70f1b..5d76a6a 100644
--- a/pkgmk.conf
+++ b/pkgmk.conf
@@ -1,15 +1,16 @@
#
# /etc/pkgmk.conf: pkgmk(8) configuration
#
export CFLAGS="-O2 -march=i686 -pipe"
export CXXFLAGS="-O2 -march=i686 -pipe"
+# PKGMK_SOURCE_MIRRORS=()
# PKGMK_SOURCE_DIR="$PWD"
# PKGMK_PACKAGE_DIR="$PWD"
# PKGMK_WORK_DIR="$PWD/work"
# PKGMK_DOWNLOAD="no"
# PKGMK_IGNORE_FOOTPRINT="no"
# PKGMK_NO_STRIP="no"
# End of file
diff --git a/pkgmk.in b/pkgmk.in
index 67425e0..da9b303 100755
--- a/pkgmk.in
+++ b/pkgmk.in
@@ -1,657 +1,678 @@
#!/bin/bash
#
# pkgutils
#
# Copyright (c) 2000-2005 Per Liden
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
info() {
echo "=======> $1"
}
warning() {
info "WARNING: $1" >&2
}
error() {
info "ERROR: $1" >&2
}
get_filename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
if [ "$FILE" != "$1" ]; then
FILE="$PKGMK_SOURCE_DIR/$FILE"
fi
echo $FILE
}
+get_basename() {
+ local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
+ echo $FILE
+}
+
check_pkgfile() {
if [ ! "$name" ]; then
error "Variable 'name' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$version" ]; then
error "Variable 'version' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$release" ]; then
error "Variable 'release' not specified in $PKGMK_PKGFILE."
exit 1
elif [ "`type -t build`" != "function" ]; then
error "Function 'build' not specified in $PKGMK_PKGFILE."
exit 1
fi
}
check_directory() {
if [ ! -d $1 ]; then
error "Directory '$1' does not exist."
exit 1
elif [ ! -w $1 ]; then
error "Directory '$1' not writable."
exit 1
elif [ ! -x $1 ] || [ ! -r $1 ]; then
error "Directory '$1' not readable."
exit 1
fi
}
download_file() {
info "Downloading '$1'."
if [ ! "`type -p wget`" ]; then
error "Command 'wget' not found."
exit 1
fi
LOCAL_FILENAME=`get_filename $1`
LOCAL_FILENAME_PARTIAL="$LOCAL_FILENAME.partial"
- DOWNLOAD_CMD="--passive-ftp --no-directories --tries=3 --waitretry=3 \
- --directory-prefix=$PKGMK_SOURCE_DIR --output-document=$LOCAL_FILENAME_PARTIAL $1"
+ DOWNLOAD_OPTS="--passive-ftp --no-directories --tries=3 --waitretry=3 \
+ --directory-prefix=$PKGMK_SOURCE_DIR \
+ --output-document=$LOCAL_FILENAME_PARTIAL"
if [ -f "$LOCAL_FILENAME_PARTIAL" ]; then
info "Partial download found, trying to resume"
RESUME_CMD="-c"
fi
- while true; do
- wget $RESUME_CMD $DOWNLOAD_CMD
+ error=1
+
+ BASENAME=`get_basename $1`
+ for REPO in ${PKGMK_SOURCE_MIRRORS[@]}; do
+ REPO="`echo $REPO | sed 's|/$||'`"
+ wget $RESUME_CMD $DOWNLOAD_OPTS $REPO/$BASENAME
error=$?
- if [ $error != 0 ] && [ "$RESUME_CMD" ]; then
- info "Partial download failed, restarting"
- rm -f "$LOCAL_FILENAME_PARTIAL"
- RESUME_CMD=""
- else
+ if [ $error == 0 ]; then
break
fi
done
+
+ if [ $error != 0 ]; then
+ while true; do
+ wget $RESUME_CMD $DOWNLOAD_OPTS $1
+ error=$?
+ if [ $error != 0 ] && [ "$RESUME_CMD" ]; then
+ info "Partial download failed, restarting"
+ rm -f "$LOCAL_FILENAME_PARTIAL"
+ RESUME_CMD=""
+ else
+ break
+ fi
+ done
+ fi
if [ $error != 0 ]; then
error "Downloading '$1' failed."
exit 1
fi
mv -f "$LOCAL_FILENAME_PARTIAL" "$LOCAL_FILENAME"
}
download_source() {
local FILE LOCAL_FILENAME
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ ! -e $LOCAL_FILENAME ]; then
if [ "$LOCAL_FILENAME" = "$FILE" ]; then
error "Source file '$LOCAL_FILENAME' not found (can not be downloaded, URL not specified)."
exit 1
else
if [ "$PKGMK_DOWNLOAD" = "yes" ]; then
download_file $FILE
else
error "Source file '$LOCAL_FILENAME' not found (use option -d to download)."
exit 1
fi
fi
fi
done
}
unpack_source() {
local FILE LOCAL_FILENAME COMMAND
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
case $LOCAL_FILENAME in
*.tar.gz|*.tar.Z|*.tgz)
COMMAND="tar -C $SRC --use-compress-program=gzip -xf $LOCAL_FILENAME" ;;
*.tar.bz2)
COMMAND="tar -C $SRC --use-compress-program=bzip2 -xf $LOCAL_FILENAME" ;;
*.zip)
COMMAND="unzip -qq -o -d $SRC $LOCAL_FILENAME" ;;
*)
COMMAND="cp $LOCAL_FILENAME $SRC" ;;
esac
echo "$COMMAND"
$COMMAND
if [ $? != 0 ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
error "Building '$TARGET' failed."
exit 1
fi
done
}
make_md5sum() {
local FILE LOCAL_FILENAMES
if [ "$source" ]; then
for FILE in ${source[@]}; do
LOCAL_FILENAMES="$LOCAL_FILENAMES `get_filename $FILE`"
done
md5sum $LOCAL_FILENAMES | sed -e 's| .*/| |' | sort -k 2
fi
}
make_footprint() {
pkginfo --footprint $TARGET | \
sed "s|\tlib/modules/`uname -r`/|\tlib/modules/<kernel-version>/|g" | \
sort -k 3
}
check_md5sum() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $PKGMK_MD5SUM ]; then
make_md5sum > $FILE.md5sum
sort -k 2 $PKGMK_MD5SUM > $FILE.md5sum.orig
diff -w -t -U 0 $FILE.md5sum.orig $FILE.md5sum | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.md5sum.diff
if [ -s $FILE.md5sum.diff ]; then
error "Md5sum mismatch found:"
cat $FILE.md5sum.diff >&2
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
error "Md5sum not ok."
exit 1
fi
error "Building '$TARGET' failed."
exit 1
fi
else
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum not found."
exit 1
fi
warning "Md5sum not found, creating new."
make_md5sum > $PKGMK_MD5SUM
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum ok."
exit 0
fi
}
strip_files() {
local FILE FILTER
cd $PKG
if [ -f $PKGMK_ROOT/$PKGMK_NOSTRIP ]; then
FILTER="grep -v -f $PKGMK_ROOT/$PKGMK_NOSTRIP"
else
FILTER="cat"
fi
find . -type f -printf "%P\n" | $FILTER | while read FILE; do
case $(file -b "$FILE") in
*ELF*executable*not\ stripped)
strip --strip-all "$FILE"
;;
*ELF*shared\ object*not\ stripped)
strip --strip-unneeded "$FILE"
;;
current\ ar\ archive)
strip --strip-debug "$FILE"
esac
done
}
compress_manpages() {
local FILE DIR TARGET
cd $PKG
find . -type f -path "*/man/man*/*" | while read FILE; do
if [ "$FILE" = "${FILE%%.gz}" ]; then
gzip -9 "$FILE"
fi
done
find . -type l -path "*/man/man*/*" | while read FILE; do
TARGET=`readlink -n "$FILE"`
TARGET="${TARGET##*/}"
TARGET="${TARGET%%.gz}.gz"
rm -f "$FILE"
FILE="${FILE%%.gz}.gz"
DIR=`dirname "$FILE"`
if [ -e "$DIR/$TARGET" ]; then
ln -sf "$TARGET" "$FILE"
fi
done
}
check_footprint() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $TARGET ]; then
make_footprint > $FILE.footprint
if [ -f $PKGMK_FOOTPRINT ]; then
sort -k 3 $PKGMK_FOOTPRINT > $FILE.footprint.orig
diff -w -t -U 0 $FILE.footprint.orig $FILE.footprint | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.footprint.diff
if [ -s $FILE.footprint.diff ]; then
error "Footprint mismatch found:"
cat $FILE.footprint.diff >&2
BUILD_SUCCESSFUL="no"
fi
else
warning "Footprint not found, creating new."
mv $FILE.footprint $PKGMK_FOOTPRINT
fi
else
error "Package '$TARGET' was not found."
BUILD_SUCCESSFUL="no"
fi
}
build_package() {
local BUILD_SUCCESSFUL="no"
export PKG="$PKGMK_WORK_DIR/pkg"
export SRC="$PKGMK_WORK_DIR/src"
umask 022
cd $PKGMK_ROOT
rm -rf $PKGMK_WORK_DIR
mkdir -p $SRC $PKG
if [ "$PKGMK_IGNORE_MD5SUM" = "no" ]; then
check_md5sum
fi
if [ "$UID" != "0" ]; then
warning "Packages should be built as root."
fi
info "Building '$TARGET'."
unpack_source
cd $SRC
(set -e -x ; build)
if [ $? = 0 ]; then
if [ "$PKGMK_NO_STRIP" = "no" ]; then
strip_files
fi
compress_manpages
cd $PKG
info "Build result:"
tar czvvf $TARGET *
if [ $? = 0 ]; then
BUILD_SUCCESSFUL="yes"
if [ "$PKGMK_IGNORE_FOOTPRINT" = "yes" ]; then
warning "Footprint ignored."
else
check_footprint
fi
fi
fi
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$BUILD_SUCCESSFUL" = "yes" ]; then
info "Building '$TARGET' succeeded."
else
if [ -f $TARGET ]; then
touch -r $PKGMK_ROOT/$PKGMK_PKGFILE $TARGET &> /dev/null
fi
error "Building '$TARGET' failed."
exit 1
fi
}
install_package() {
local COMMAND
info "Installing '$TARGET'."
if [ "$PKGMK_INSTALL" = "install" ]; then
COMMAND="pkgadd $TARGET"
else
COMMAND="pkgadd -u $TARGET"
fi
cd $PKGMK_ROOT
echo "$COMMAND"
$COMMAND
if [ $? = 0 ]; then
info "Installing '$TARGET' succeeded."
else
error "Installing '$TARGET' failed."
exit 1
fi
}
recursive() {
local ARGS FILE DIR
ARGS=`echo "$@" | sed -e "s/--recursive//g" -e "s/-r//g"`
for FILE in `find $PKGMK_ROOT -name $PKGMK_PKGFILE | sort`; do
DIR="`dirname $FILE`/"
if [ -d $DIR ]; then
info "Entering directory '$DIR'."
(cd $DIR && $PKGMK_COMMAND $ARGS)
info "Leaving directory '$DIR'."
fi
done
}
clean() {
local FILE LOCAL_FILENAME
if [ -f $TARGET ]; then
info "Removing $TARGET"
rm -f $TARGET
fi
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ -e $LOCAL_FILENAME ] && [ "$LOCAL_FILENAME" != "$FILE" ]; then
info "Removing $LOCAL_FILENAME"
rm -f $LOCAL_FILENAME
fi
done
}
update_footprint() {
if [ ! -f $TARGET ]; then
error "Unable to update footprint. File '$TARGET' not found."
exit 1
fi
make_footprint > $PKGMK_FOOTPRINT
touch $TARGET
info "Footprint updated."
}
build_needed() {
local FILE RESULT
RESULT="yes"
if [ -f $TARGET ]; then
RESULT="no"
for FILE in $PKGMK_PKGFILE ${source[@]}; do
FILE=`get_filename $FILE`
if [ ! -e $FILE ] || [ ! $TARGET -nt $FILE ]; then
RESULT="yes"
break
fi
done
fi
echo $RESULT
}
interrupted() {
echo ""
error "Interrupted."
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
exit 1
}
print_help() {
echo "usage: `basename $PKGMK_COMMAND` [options]"
echo "options:"
echo " -i, --install build and install package"
echo " -u, --upgrade build and install package (as upgrade)"
echo " -r, --recursive search for and build packages recursively"
echo " -d, --download download missing source file(s)"
echo " -do, --download-only do not build, only download missing source file(s)"
echo " -utd, --up-to-date do not build, only check if package is up to date"
echo " -uf, --update-footprint update footprint using result from last build"
echo " -if, --ignore-footprint build package without checking footprint"
echo " -um, --update-md5sum update md5sum"
echo " -im, --ignore-md5sum build package without checking md5sum"
echo " -cm, --check-md5sum do not build, only check md5sum"
echo " -ns, --no-strip do not strip executable binaries or libraries"
echo " -f, --force build package even if it appears to be up to date"
echo " -c, --clean remove package and downloaded files"
echo " -kw, --keep-work keep temporary working directory"
echo " -cf, --config-file <file> use alternative configuration file"
echo " -v, --version print version and exit "
echo " -h, --help print help and exit"
}
parse_options() {
while [ "$1" ]; do
case $1 in
-i|--install)
PKGMK_INSTALL="install" ;;
-u|--upgrade)
PKGMK_INSTALL="upgrade" ;;
-r|--recursive)
PKGMK_RECURSIVE="yes" ;;
-d|--download)
PKGMK_DOWNLOAD="yes" ;;
-do|--download-only)
PKGMK_DOWNLOAD="yes"
PKGMK_DOWNLOAD_ONLY="yes" ;;
-utd|--up-to-date)
PKGMK_UP_TO_DATE="yes" ;;
-uf|--update-footprint)
PKGMK_UPDATE_FOOTPRINT="yes" ;;
-if|--ignore-footprint)
PKGMK_IGNORE_FOOTPRINT="yes" ;;
-um|--update-md5sum)
PKGMK_UPDATE_MD5SUM="yes" ;;
-im|--ignore-md5sum)
PKGMK_IGNORE_MD5SUM="yes" ;;
-cm|--check-md5sum)
PKGMK_CHECK_MD5SUM="yes" ;;
-ns|--no-strip)
PKGMK_NO_STRIP="yes" ;;
-f|--force)
PKGMK_FORCE="yes" ;;
-c|--clean)
PKGMK_CLEAN="yes" ;;
-kw|--keep-work)
PKGMK_KEEP_WORK="yes" ;;
-cf|--config-file)
if [ ! "$2" ]; then
echo "`basename $PKGMK_COMMAND`: option $1 requires an argument"
exit 1
fi
PKGMK_CONFFILE="$2"
shift ;;
-v|--version)
echo "`basename $PKGMK_COMMAND` (pkgutils) $PKGMK_VERSION"
exit 0 ;;
-h|--help)
print_help
exit 0 ;;
*)
echo "`basename $PKGMK_COMMAND`: invalid option $1"
exit 1 ;;
esac
shift
done
}
main() {
local FILE TARGET
parse_options "$@"
if [ "$PKGMK_RECURSIVE" = "yes" ]; then
recursive "$@"
exit 0
fi
for FILE in $PKGMK_PKGFILE $PKGMK_CONFFILE; do
if [ ! -f $FILE ]; then
error "File '$FILE' not found."
exit 1
fi
. $FILE
done
check_directory "$PKGMK_SOURCE_DIR"
check_directory "$PKGMK_PACKAGE_DIR"
check_directory "`dirname $PKGMK_WORK_DIR`"
check_pkgfile
TARGET="$PKGMK_PACKAGE_DIR/$name#$version-$release.pkg.tar.gz"
if [ "$PKGMK_CLEAN" = "yes" ]; then
clean
exit 0
fi
if [ "$PKGMK_UPDATE_FOOTPRINT" = "yes" ]; then
update_footprint
exit 0
fi
if [ "$PKGMK_UPDATE_MD5SUM" = "yes" ]; then
download_source
make_md5sum > $PKGMK_MD5SUM
info "Md5sum updated."
exit 0
fi
if [ "$PKGMK_DOWNLOAD_ONLY" = "yes" ]; then
download_source
exit 0
fi
if [ "$PKGMK_UP_TO_DATE" = "yes" ]; then
if [ "`build_needed`" = "yes" ]; then
info "Package '$TARGET' is not up to date."
else
info "Package '$TARGET' is up to date."
fi
exit 0
fi
if [ "`build_needed`" = "no" ] && [ "$PKGMK_FORCE" = "no" ] && [ "$PKGMK_CHECK_MD5SUM" = "no" ]; then
info "Package '$TARGET' is up to date."
else
download_source
build_package
fi
if [ "$PKGMK_INSTALL" != "no" ]; then
install_package
fi
exit 0
}
trap "interrupted" SIGHUP SIGINT SIGQUIT SIGTERM
export LC_ALL=POSIX
readonly PKGMK_VERSION="#VERSION#"
readonly PKGMK_COMMAND="$0"
readonly PKGMK_ROOT="$PWD"
PKGMK_CONFFILE="/etc/pkgmk.conf"
PKGMK_PKGFILE="Pkgfile"
PKGMK_FOOTPRINT=".footprint"
PKGMK_MD5SUM=".md5sum"
PKGMK_NOSTRIP=".nostrip"
+PKGMK_SOURCE_MIRRORS=()
PKGMK_SOURCE_DIR="$PWD"
PKGMK_PACKAGE_DIR="$PWD"
PKGMK_WORK_DIR="$PWD/work"
PKGMK_INSTALL="no"
PKGMK_RECURSIVE="no"
PKGMK_DOWNLOAD="no"
PKGMK_DOWNLOAD_ONLY="no"
PKGMK_UP_TO_DATE="no"
PKGMK_UPDATE_FOOTPRINT="no"
PKGMK_IGNORE_FOOTPRINT="no"
PKGMK_FORCE="no"
PKGMK_KEEP_WORK="no"
PKGMK_UPDATE_MD5SUM="no"
PKGMK_IGNORE_MD5SUM="no"
PKGMK_CHECK_MD5SUM="no"
PKGMK_NO_STRIP="no"
PKGMK_CLEAN="no"
main "$@"
# End of file
|
nipuL/pkgutils | 86830d3c84fef2d68fee2def7a276caaa94d72f4 | Improved "dist" target. | diff --git a/Makefile b/Makefile
index 958f08d..67c334c 100644
--- a/Makefile
+++ b/Makefile
@@ -1,100 +1,100 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
# Copyright (c) 2006-2007 by CRUX team (http://crux.nu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
VERSION = 5.30.0
+NAME = pkgutils-$(VERSION)
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDFLAGS += -static -larchive -lz -lbz2
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
all: pkgadd pkgmk rejmerge man
pkgadd: .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
- rm -rf /tmp/pkgutils-$(VERSION)
- mkdir -p /tmp/pkgutils-$(VERSION)
- git-log > ChangeLog
- cp -rf . /tmp/pkgutils-$(VERSION)
- tar -C /tmp --exclude .git -czvf ../pkgutils-$(VERSION).tar.gz pkgutils-$(VERSION)
- rm -rf /tmp/pkgutils-$(VERSION)
+ rm -rf $(NAME) $(NAME).tar.gz
+ git archive --format=tar --prefix=$(NAME)/ HEAD | tar -x
+ git log > $(NAME)/ChangeLog
+ tar czvf $(NAME).tar.gz $(NAME)
+ rm -rf $(NAME)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
# End of file
|
nipuL/pkgutils | 9a7adb608a4b3e207e2c80ebf316682e205c2cc6 | Don't mention libtar in README anymore. | diff --git a/README b/README
index 3fe0c15..0ec3660 100644
--- a/README
+++ b/README
@@ -1,28 +1,25 @@
pkgutils - Package Management Utilities
http://www.fukt.bth.se/~per/pkgutils/
Description
-----------
pkgutils is a set of utilities (pkgadd, pkgrm, pkginfo, pkgmk and rejmerge),
which are used for managing software packages in Linux. It is developed for
and used by the CRUX distribution (http://crux.nu).
Building and installing
-----------------------
$ make
$ make install
or
$ make DESTDIR=/some/other/path install
Copyright
---------
pkgutils is Copyright (c) 2000-2005 Per Liden and is licensed through the
GNU General Public License. Read the COPYING file for the complete license.
-
-pkgutils uses libtar, a library for reading/writing tar-files. This
-library is Copyright (c) 1998-2003 Mark D. Roth.
|
nipuL/pkgutils | b3197f39a0ac2c23680450183442534e3a028cc4 | Bumped version to 5.30.0. | diff --git a/Makefile b/Makefile
index 2035ef6..8b21d2b 100644
--- a/Makefile
+++ b/Makefile
@@ -1,99 +1,99 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
-VERSION = 5.21
+VERSION = 5.30.0
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDFLAGS += -static -larchive -lz -lbz2
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
all: pkgadd pkgmk rejmerge man
pkgadd: .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
rm -rf /tmp/pkgutils-$(VERSION)
mkdir -p /tmp/pkgutils-$(VERSION)
git-log > ChangeLog
cp -rf . /tmp/pkgutils-$(VERSION)
tar -C /tmp --exclude .git -czvf ../pkgutils-$(VERSION).tar.gz pkgutils-$(VERSION)
rm -rf /tmp/pkgutils-$(VERSION)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
# End of file
|
nipuL/pkgutils | c9984aa86ec99c6dd8d47c2bf3d7a409a1c4fa48 | Moved archive initialization code to INIT_ARCHIVE. | diff --git a/pkgutil.cc b/pkgutil.cc
index 943c420..00cedaf 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,810 +1,810 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
+#define INIT_ARCHIVE(ar) \
+ archive_read_support_compression_all((ar)); \
+ archive_read_support_format_all((ar))
+
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
- archive_read_support_compression_all(archive);
- archive_read_support_format_all(archive);
+ INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
mode_t mode = archive_entry_mode(entry);
if (S_ISREG(mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
- archive_read_support_compression_all(archive);
- archive_read_support_format_all(archive);
+ INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
mode_t mode;
cout << utilname << ": ignoring " << archive_filename << endl;
mode = archive_entry_mode(entry);
if (S_ISREG(mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
unsigned int flags = ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_UNLINK;
if (archive_read_extract(archive, entry, flags) != ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
mode_t mode = archive_entry_mode(entry);
// Directory
if (S_ISDIR(mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
map<string, mode_t> hardlink_target_modes;
// We first do a run over the archive and remember the modes
// of regular files.
// In the second run, we print the footprint - using the stored
// modes for hardlinks.
//
// FIXME the code duplication here is butt ugly
archive = archive_read_new();
- archive_read_support_compression_all(archive);
- archive_read_support_format_all(archive);
+ INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
if (!archive_entry_hardlink(entry)) {
const char *s = archive_entry_pathname(entry);
hardlink_target_modes[s] = mode;
}
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
archive_read_finish(archive);
// Too bad, there doesn't seem to be a way to reuse our archive
// instance
archive = archive_read_new();
- archive_read_support_compression_all(archive);
- archive_read_support_format_all(archive);
+ INIT_ARCHIVE(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
// Access permissions
if (S_ISLNK(mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
const char *h = archive_entry_hardlink(entry);
if (h)
cout << mtos(hardlink_target_modes[h]);
else
cout << mtos(mode);
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(mode) ||
S_ISBLK(mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | bfb5480be95ac565f1a057750429857385478be9 | bug #107: upgrade udev rules by default. | diff --git a/pkgadd.conf b/pkgadd.conf
index aa399b3..ae18261 100644
--- a/pkgadd.conf
+++ b/pkgadd.conf
@@ -1,23 +1,26 @@
#
# /etc/pkgadd.conf: pkgadd(8) configuration
#
# Default rule (implicit)
#UPGRADE ^.*$ YES
UPGRADE ^etc/.*$ NO
UPGRADE ^var/log/.*$ NO
UPGRADE ^var/spool/\w*cron/.*$ NO
UPGRADE ^var/run/utmp$ NO
UPGRADE ^etc/mail/cf/.*$ YES
UPGRADE ^etc/ports/drivers/.*$ YES
UPGRADE ^etc/X11/.*$ YES
UPGRADE ^etc/rc.*$ YES
UPGRADE ^etc/rc\.local$ NO
UPGRADE ^etc/rc\.modules$ NO
UPGRADE ^etc/rc\.conf$ NO
UPGRADE ^etc/rc\.d/net$ NO
+UPGRADE ^etc/udev/rules.d/.*$ YES
+UPGRADE ^etc/udev/rules.d/1.*$ NO
+
# End of file
|
nipuL/pkgutils | 9fb2521b153582faf2d79e29f44421d34c2b6ae1 | Removed some dead (and buggy) code. | diff --git a/pkgutil.cc b/pkgutil.cc
index 62a9edf..943c420 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,847 +1,810 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
-#include <zlib.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
mode_t mode = archive_entry_mode(entry);
if (S_ISREG(mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
mode_t mode;
cout << utilname << ": ignoring " << archive_filename << endl;
mode = archive_entry_mode(entry);
if (S_ISREG(mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
unsigned int flags = ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_UNLINK;
if (archive_read_extract(archive, entry, flags) != ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
mode_t mode = archive_entry_mode(entry);
// Directory
if (S_ISDIR(mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
map<string, mode_t> hardlink_target_modes;
// We first do a run over the archive and remember the modes
// of regular files.
// In the second run, we print the footprint - using the stored
// modes for hardlinks.
//
// FIXME the code duplication here is butt ugly
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
if (!archive_entry_hardlink(entry)) {
const char *s = archive_entry_pathname(entry);
hardlink_target_modes[s] = mode;
}
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
archive_read_finish(archive);
// Too bad, there doesn't seem to be a way to reuse our archive
// instance
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
// Access permissions
if (S_ISLNK(mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
const char *h = archive_entry_hardlink(entry);
if (h)
cout << mtos(hardlink_target_modes[h]);
else
cout << mtos(mode);
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(mode) ||
S_ISBLK(mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
-int unistd_gzopen(char* pathname, int flags, mode_t mode)
-{
- char* gz_mode;
-
- switch (flags & O_ACCMODE) {
- case O_WRONLY:
- gz_mode = "w";
- break;
-
- case O_RDONLY:
- gz_mode = "r";
- break;
-
- case O_RDWR:
- default:
- errno = EINVAL;
- return -1;
- }
-
- int fd;
- gzFile gz_file;
-
- if ((fd = open(pathname, flags, mode)) == -1)
- return -1;
-
- if ((flags & O_CREAT) && fchmod(fd, mode))
- return -1;
-
- if (!(gz_file = gzdopen(fd, gz_mode))) {
- errno = ENOMEM;
- return -1;
- }
-
- return (int)gz_file;
-}
-
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
diff --git a/pkgutil.h b/pkgutil.h
index 03409df..d950352 100644
--- a/pkgutil.h
+++ b/pkgutil.h
@@ -1,110 +1,109 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#ifndef PKGUTIL_H
#define PKGUTIL_H
#include <string>
#include <set>
#include <map>
#include <iostream>
#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <dirent.h>
#define PKG_EXT ".pkg.tar.gz"
#define PKG_DIR "var/lib/pkg"
#define PKG_DB "var/lib/pkg/db"
#define PKG_REJECTED "var/lib/pkg/rejected"
#define VERSION_DELIM '#'
#define LDCONFIG "/sbin/ldconfig"
#define LDCONFIG_CONF "/etc/ld.so.conf"
using namespace std;
class pkgutil {
public:
struct pkginfo_t {
string version;
set<string> files;
};
typedef map<string, pkginfo_t> packages_t;
explicit pkgutil(const string& name);
virtual ~pkgutil() {}
virtual void run(int argc, char** argv) = 0;
virtual void print_help() const = 0;
void print_version() const;
protected:
// Database
void db_open(const string& path);
void db_commit();
void db_add_pkg(const string& name, const pkginfo_t& info);
bool db_find_pkg(const string& name);
void db_rm_pkg(const string& name);
void db_rm_pkg(const string& name, const set<string>& keep_list);
void db_rm_files(set<string> files, const set<string>& keep_list);
set<string> db_find_conflicts(const string& name, const pkginfo_t& info);
// Tar.gz
pair<string, pkginfo_t> pkg_open(const string& filename) const;
void pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_files) const;
void pkg_footprint(string& filename) const;
void ldconfig() const;
string utilname;
packages_t packages;
string root;
};
class db_lock {
public:
db_lock(const string& root, bool exclusive);
~db_lock();
private:
DIR* dir;
};
class runtime_error_with_errno : public runtime_error {
public:
explicit runtime_error_with_errno(const string& msg) throw()
: runtime_error(msg + string(": ") + strerror(errno)) {}
explicit runtime_error_with_errno(const string& msg, int e) throw()
: runtime_error(msg + string(": ") + strerror(e)) {}
};
// Utility functions
void assert_argument(char** argv, int argc, int index);
string itos(unsigned int value);
string mtos(mode_t mode);
-int unistd_gzopen(char* pathname, int flags, mode_t mode);
string trim_filename(const string& filename);
bool file_exists(const string& filename);
bool file_empty(const string& filename);
bool file_equal(const string& file1, const string& file2);
bool permissions_equal(const string& file1, const string& file2);
void file_remove(const string& basedir, const string& filename);
#endif /* PKGUTIL_H */
|
nipuL/pkgutils | 2a62ed9ad2688a873bc7773b2c3cf818456aeabb | Set ARCHIVE_EXTRACT_UNLINK when extracting archive entries. | diff --git a/pkgutil.cc b/pkgutil.cc
index f5b430d..62a9edf 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,846 +1,847 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
mode_t mode = archive_entry_mode(entry);
if (S_ISREG(mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
mode_t mode;
cout << utilname << ": ignoring " << archive_filename << endl;
mode = archive_entry_mode(entry);
if (S_ISREG(mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
- if (archive_read_extract(archive, entry, ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM) !=
- ARCHIVE_OK) {
+ unsigned int flags = ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_UNLINK;
+
+ if (archive_read_extract(archive, entry, flags) != ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
mode_t mode = archive_entry_mode(entry);
// Directory
if (S_ISDIR(mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
map<string, mode_t> hardlink_target_modes;
// We first do a run over the archive and remember the modes
// of regular files.
// In the second run, we print the footprint - using the stored
// modes for hardlinks.
//
// FIXME the code duplication here is butt ugly
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
if (!archive_entry_hardlink(entry)) {
const char *s = archive_entry_pathname(entry);
hardlink_target_modes[s] = mode;
}
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
archive_read_finish(archive);
// Too bad, there doesn't seem to be a way to reuse our archive
// instance
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
// Access permissions
if (S_ISLNK(mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
const char *h = archive_entry_hardlink(entry);
if (h)
cout << mtos(hardlink_target_modes[h]);
else
cout << mtos(mode);
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(mode) ||
S_ISBLK(mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | e83769cac3e8ccbe57b287467746c9c1a7254136 | Fixed setting up the flags for archive_read_extract(). | diff --git a/pkgutil.cc b/pkgutil.cc
index b4d419b..f5b430d 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,846 +1,846 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
mode_t mode = archive_entry_mode(entry);
if (S_ISREG(mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
mode_t mode;
cout << utilname << ": ignoring " << archive_filename << endl;
mode = archive_entry_mode(entry);
if (S_ISREG(mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
- if (archive_read_extract(archive, entry, ARCHIVE_EXTRACT_OWNER && ARCHIVE_EXTRACT_PERM) !=
+ if (archive_read_extract(archive, entry, ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM) !=
ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
mode_t mode = archive_entry_mode(entry);
// Directory
if (S_ISDIR(mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
map<string, mode_t> hardlink_target_modes;
// We first do a run over the archive and remember the modes
// of regular files.
// In the second run, we print the footprint - using the stored
// modes for hardlinks.
//
// FIXME the code duplication here is butt ugly
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
if (!archive_entry_hardlink(entry)) {
const char *s = archive_entry_pathname(entry);
hardlink_target_modes[s] = mode;
}
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
archive_read_finish(archive);
// Too bad, there doesn't seem to be a way to reuse our archive
// instance
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
// Access permissions
if (S_ISLNK(mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
const char *h = archive_entry_hardlink(entry);
if (h)
cout << mtos(hardlink_target_modes[h]);
else
cout << mtos(mode);
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(mode) ||
S_ISBLK(mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | 25efd91b9eec7755e4296591f531c923209dd1fa | preserve owner/permissions when extracting | diff --git a/pkgutil.cc b/pkgutil.cc
index ce94501..b4d419b 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,846 +1,846 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
mode_t mode = archive_entry_mode(entry);
if (S_ISREG(mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
mode_t mode;
cout << utilname << ": ignoring " << archive_filename << endl;
mode = archive_entry_mode(entry);
if (S_ISREG(mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
- if (archive_read_extract(archive, entry, 0) !=
+ if (archive_read_extract(archive, entry, ARCHIVE_EXTRACT_OWNER && ARCHIVE_EXTRACT_PERM) !=
ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
mode_t mode = archive_entry_mode(entry);
// Directory
if (S_ISDIR(mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
map<string, mode_t> hardlink_target_modes;
// We first do a run over the archive and remember the modes
// of regular files.
// In the second run, we print the footprint - using the stored
// modes for hardlinks.
//
// FIXME the code duplication here is butt ugly
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
if (!archive_entry_hardlink(entry)) {
const char *s = archive_entry_pathname(entry);
hardlink_target_modes[s] = mode;
}
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
archive_read_finish(archive);
// Too bad, there doesn't seem to be a way to reuse our archive
// instance
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
// Access permissions
if (S_ISLNK(mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
const char *h = archive_entry_hardlink(entry);
if (h)
cout << mtos(hardlink_target_modes[h]);
else
cout << mtos(mode);
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(mode) ||
S_ISBLK(mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | 80db05ef8d1a1ce7d7948a9d06732209f5f84fce | Fixed the permission lookup problem for hardlinks. | diff --git a/pkgutil.cc b/pkgutil.cc
index 54c80b6..ce94501 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,805 +1,846 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
mode_t mode = archive_entry_mode(entry);
if (S_ISREG(mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
mode_t mode;
cout << utilname << ": ignoring " << archive_filename << endl;
mode = archive_entry_mode(entry);
if (S_ISREG(mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
if (archive_read_extract(archive, entry, 0) !=
ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
mode_t mode = archive_entry_mode(entry);
// Directory
if (S_ISDIR(mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
+ map<string, mode_t> hardlink_target_modes;
+
+ // We first do a run over the archive and remember the modes
+ // of regular files.
+ // In the second run, we print the footprint - using the stored
+ // modes for hardlinks.
+ //
+ // FIXME the code duplication here is butt ugly
+ archive = archive_read_new();
+ archive_read_support_compression_all(archive);
+ archive_read_support_format_all(archive);
+
+ if (archive_read_open_filename(archive,
+ const_cast<char*>(filename.c_str()),
+ ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
+ throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
+
+ for (i = 0; archive_read_next_header(archive, &entry) ==
+ ARCHIVE_OK; ++i) {
+
+ mode_t mode = archive_entry_mode(entry);
+
+ if (!archive_entry_hardlink(entry)) {
+ const char *s = archive_entry_pathname(entry);
+
+ hardlink_target_modes[s] = mode;
+ }
+
+ if (S_ISREG(mode) && archive_read_data_skip(archive))
+ throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
+ }
+
+ archive_read_finish(archive);
+
+ // Too bad, there doesn't seem to be a way to reuse our archive
+ // instance
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
mode_t mode = archive_entry_mode(entry);
// Access permissions
if (S_ISLNK(mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
- cout << mtos(mode);
+ const char *h = archive_entry_hardlink(entry);
+
+ if (h)
+ cout << mtos(hardlink_target_modes[h]);
+ else
+ cout << mtos(mode);
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(mode) ||
S_ISBLK(mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | 7f84e1cc9e8e7ae698e8b648f7dbba98a2753150 | Prefer archive_entry_mode() over archive_entry_stat(). | diff --git a/pkgutil.cc b/pkgutil.cc
index 33ee301..54c80b6 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,810 +1,805 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
- const struct stat* status;
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
- status = archive_entry_stat(entry);
+ mode_t mode = archive_entry_mode(entry);
- if (S_ISREG(status->st_mode) &&
+ if (S_ISREG(mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
- const struct stat* status;
+ mode_t mode;
cout << utilname << ": ignoring " << archive_filename << endl;
- status = archive_entry_stat(entry);
+ mode = archive_entry_mode(entry);
- if (S_ISREG(status->st_mode))
+ if (S_ISREG(mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
if (archive_read_extract(archive, entry, 0) !=
ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
- const struct stat* status;
-
- status = archive_entry_stat(entry);
+ mode_t mode = archive_entry_mode(entry);
// Directory
- if (S_ISDIR(status->st_mode))
+ if (S_ISDIR(mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
- const struct stat* status;
-
- status = archive_entry_stat(entry);
+ mode_t mode = archive_entry_mode(entry);
// Access permissions
- if (S_ISLNK(status->st_mode)) {
+ if (S_ISLNK(mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
- cout << mtos(archive_entry_mode(entry));
+ cout << mtos(mode);
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
- if (S_ISLNK(status->st_mode)) {
+ if (S_ISLNK(mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
- } else if (S_ISCHR(status->st_mode) ||
- S_ISBLK(status->st_mode)) {
+ } else if (S_ISCHR(mode) ||
+ S_ISBLK(mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
- } else if (S_ISREG(status->st_mode) &&
+ } else if (S_ISREG(mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
- if (S_ISREG(status->st_mode) && archive_read_data_skip(archive))
+ if (S_ISREG(mode) && archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | fa6b0879f2c91662cdef26b598889b9834196805 | Some indentation fixes. | diff --git a/pkgutil.cc b/pkgutil.cc
index 1354365..33ee301 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,811 +1,810 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
const struct stat* status;
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
status = archive_entry_stat(entry);
if (S_ISREG(status->st_mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
const struct stat* status;
cout << utilname << ": ignoring " << archive_filename << endl;
status = archive_entry_stat(entry);
if (S_ISREG(status->st_mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
if (archive_read_extract(archive, entry, 0) !=
ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
const struct stat* status;
status = archive_entry_stat(entry);
// Directory
if (S_ISDIR(status->st_mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
- unsigned int i;
+ unsigned int i;
struct archive* archive;
struct archive_entry* entry;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
const struct stat* status;
status = archive_entry_stat(entry);
// Access permissions
if (S_ISLNK(status->st_mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
cout << mtos(archive_entry_mode(entry));
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(status->st_mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(status->st_mode) ||
S_ISBLK(status->st_mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(status->st_mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
- if (S_ISREG(status->st_mode) &&
- archive_read_data_skip(archive))
- throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
- }
+ if (S_ISREG(status->st_mode) && archive_read_data_skip(archive))
+ throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
+ }
- if (i == 0) {
+ if (i == 0) {
if (archive_errno(archive) == 0)
- throw runtime_error("empty package");
- else
- throw runtime_error("could not read " + filename);
- }
+ throw runtime_error("empty package");
+ else
+ throw runtime_error("could not read " + filename);
+ }
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | 25f9975ca5d5010bd4f5cbfbb9faa1fed71b3db4 | Use archive_errno() instead of errno for libarchive errors. | diff --git a/pkgutil.cc b/pkgutil.cc
index 39f68f5..1354365 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,811 +1,811 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <archive.h>
#include <archive_entry.h>
using __gnu_cxx::stdio_filebuf;
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
- throw runtime_error_with_errno("could not open " + filename);
+ throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
const struct stat* status;
result.second.files.insert(result.second.files.end(),
archive_entry_pathname(entry));
status = archive_entry_stat(entry);
if (S_ISREG(status->st_mode) &&
archive_read_data_skip(archive) != ARCHIVE_OK)
- throw runtime_error_with_errno("could not read " + filename);
+ throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
struct archive* archive;
struct archive_entry* entry;
unsigned int i;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
- throw runtime_error_with_errno("could not open " + filename);
+ throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
chdir(root.c_str());
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
const struct stat* status;
cout << utilname << ": ignoring " << archive_filename << endl;
status = archive_entry_stat(entry);
if (S_ISREG(status->st_mode))
archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
archive_entry_set_pathname(entry, const_cast<char*>
(real_filename.c_str()));
// Extract file
if (archive_read_extract(archive, entry, 0) !=
ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
const struct stat* status;
status = archive_entry_stat(entry);
// Directory
if (S_ISDIR(status->st_mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
struct archive* archive;
struct archive_entry* entry;
archive = archive_read_new();
archive_read_support_compression_all(archive);
archive_read_support_format_all(archive);
if (archive_read_open_filename(archive,
const_cast<char*>(filename.c_str()),
ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
- throw runtime_error_with_errno("could not open " + filename);
+ throw runtime_error_with_errno("could not open " + filename, archive_errno(archive));
for (i = 0; archive_read_next_header(archive, &entry) ==
ARCHIVE_OK; ++i) {
const struct stat* status;
status = archive_entry_stat(entry);
// Access permissions
if (S_ISLNK(status->st_mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
cout << mtos(archive_entry_mode(entry));
}
cout << '\t';
// User
uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << archive_entry_pathname(entry);
// Special cases
if (S_ISLNK(status->st_mode)) {
// Symlink
cout << " -> " << archive_entry_symlink(entry);
} else if (S_ISCHR(status->st_mode) ||
S_ISBLK(status->st_mode)) {
// Device
cout << " (" << archive_entry_rdevmajor(entry)
<< ", " << archive_entry_rdevminor(entry)
<< ")";
} else if (S_ISREG(status->st_mode) &&
archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (S_ISREG(status->st_mode) &&
archive_read_data_skip(archive))
- throw runtime_error_with_errno("could not read " + filename);
+ throw runtime_error_with_errno("could not read " + filename, archive_errno(archive));
}
if (i == 0) {
if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
diff --git a/pkgutil.h b/pkgutil.h
index 4c74de5..03409df 100644
--- a/pkgutil.h
+++ b/pkgutil.h
@@ -1,108 +1,110 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#ifndef PKGUTIL_H
#define PKGUTIL_H
#include <string>
#include <set>
#include <map>
#include <iostream>
#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <dirent.h>
#define PKG_EXT ".pkg.tar.gz"
#define PKG_DIR "var/lib/pkg"
#define PKG_DB "var/lib/pkg/db"
#define PKG_REJECTED "var/lib/pkg/rejected"
#define VERSION_DELIM '#'
#define LDCONFIG "/sbin/ldconfig"
#define LDCONFIG_CONF "/etc/ld.so.conf"
using namespace std;
class pkgutil {
public:
struct pkginfo_t {
string version;
set<string> files;
};
typedef map<string, pkginfo_t> packages_t;
explicit pkgutil(const string& name);
virtual ~pkgutil() {}
virtual void run(int argc, char** argv) = 0;
virtual void print_help() const = 0;
void print_version() const;
protected:
// Database
void db_open(const string& path);
void db_commit();
void db_add_pkg(const string& name, const pkginfo_t& info);
bool db_find_pkg(const string& name);
void db_rm_pkg(const string& name);
void db_rm_pkg(const string& name, const set<string>& keep_list);
void db_rm_files(set<string> files, const set<string>& keep_list);
set<string> db_find_conflicts(const string& name, const pkginfo_t& info);
// Tar.gz
pair<string, pkginfo_t> pkg_open(const string& filename) const;
void pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_files) const;
void pkg_footprint(string& filename) const;
void ldconfig() const;
string utilname;
packages_t packages;
string root;
};
class db_lock {
public:
db_lock(const string& root, bool exclusive);
~db_lock();
private:
DIR* dir;
};
class runtime_error_with_errno : public runtime_error {
public:
explicit runtime_error_with_errno(const string& msg) throw()
: runtime_error(msg + string(": ") + strerror(errno)) {}
+ explicit runtime_error_with_errno(const string& msg, int e) throw()
+ : runtime_error(msg + string(": ") + strerror(e)) {}
};
// Utility functions
void assert_argument(char** argv, int argc, int index);
string itos(unsigned int value);
string mtos(mode_t mode);
int unistd_gzopen(char* pathname, int flags, mode_t mode);
string trim_filename(const string& filename);
bool file_exists(const string& filename);
bool file_empty(const string& filename);
bool file_equal(const string& file1, const string& file2);
bool permissions_equal(const string& file1, const string& file2);
void file_remove(const string& basedir, const string& filename);
#endif /* PKGUTIL_H */
|
nipuL/pkgutils | c49e53c6c7e53e77fd7b171af0b43f6f2d19a8d7 | Added .gitignore. | diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0f6bd9c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+.depend
+*.o
+*.8
+pkgadd
+pkgmk
+rejmerge
+
|
nipuL/pkgutils | c3434674df8af13a0eab79b6784e6086fa08731f | Switched from libtar to libarchive. | diff --git a/Makefile b/Makefile
index 5c1881c..2035ef6 100644
--- a/Makefile
+++ b/Makefile
@@ -1,113 +1,99 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
VERSION = 5.21
-LIBTAR_VERSION = 1.2.11
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
- -Ilibtar-$(LIBTAR_VERSION)/lib -Ilibtar-$(LIBTAR_VERSION)/listhash \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
-LDFLAGS += -static -Llibtar-$(LIBTAR_VERSION)/lib -ltar -lz
+LDFLAGS += -static -larchive -lz -lbz2
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
-LIBTAR = libtar-$(LIBTAR_VERSION)/lib/libtar.a
-
all: pkgadd pkgmk rejmerge man
-$(LIBTAR):
- (tar xzf libtar-$(LIBTAR_VERSION).tar.gz; \
- cd libtar-$(LIBTAR_VERSION); \
- patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_mem_leak.patch; \
- patch -p1 < ../libtar-$(LIBTAR_VERSION)-reduce_mem_usage.patch; \
- patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_linkname_overflow.patch; \
- LDFLAGS="" ./configure --disable-encap --disable-encap-install; \
- make)
-
-pkgadd: $(LIBTAR) .depend $(OBJECTS)
+pkgadd: .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
rm -rf /tmp/pkgutils-$(VERSION)
mkdir -p /tmp/pkgutils-$(VERSION)
git-log > ChangeLog
cp -rf . /tmp/pkgutils-$(VERSION)
tar -C /tmp --exclude .git -czvf ../pkgutils-$(VERSION).tar.gz pkgutils-$(VERSION)
rm -rf /tmp/pkgutils-$(VERSION)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
- rm -rf libtar-$(LIBTAR_VERSION)
# End of file
diff --git a/pkgutil.cc b/pkgutil.cc
index bdc1563..39f68f5 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,764 +1,811 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
-#include <libtar.h>
+#include <archive.h>
+#include <archive_entry.h>
using __gnu_cxx::stdio_filebuf;
-static tartype_t gztype = {
- (openfunc_t)unistd_gzopen,
- (closefunc_t)gzclose,
- (readfunc_t)gzread,
- (writefunc_t)gzwrite
-};
-
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
- TAR* t;
+ struct archive* archive;
+ struct archive_entry* entry;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
- if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
+ archive = archive_read_new();
+ archive_read_support_compression_all(archive);
+ archive_read_support_format_all(archive);
+
+ if (archive_read_open_filename(archive,
+ const_cast<char*>(filename.c_str()),
+ ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename);
- for (i = 0; !th_read(t); ++i) {
- result.second.files.insert(result.second.files.end(), th_get_pathname(t));
- if (TH_ISREG(t) && tar_skip_regfile(t))
+ for (i = 0; archive_read_next_header(archive, &entry) ==
+ ARCHIVE_OK; ++i) {
+ const struct stat* status;
+
+ result.second.files.insert(result.second.files.end(),
+ archive_entry_pathname(entry));
+
+ status = archive_entry_stat(entry);
+
+ if (S_ISREG(status->st_mode) &&
+ archive_read_data_skip(archive) != ARCHIVE_OK)
throw runtime_error_with_errno("could not read " + filename);
}
if (i == 0) {
- if (errno == 0)
+ if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
- tar_close(t);
+ archive_read_finish(archive);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
- TAR* t;
+ struct archive* archive;
+ struct archive_entry* entry;
unsigned int i;
- if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
+ archive = archive_read_new();
+ archive_read_support_compression_all(archive);
+ archive_read_support_format_all(archive);
+
+ if (archive_read_open_filename(archive,
+ const_cast<char*>(filename.c_str()),
+ ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename);
- for (i = 0; !th_read(t); ++i) {
- string archive_filename = th_get_pathname(t);
+ chdir(root.c_str());
+
+ for (i = 0; archive_read_next_header(archive, &entry) ==
+ ARCHIVE_OK; ++i) {
+ string archive_filename = archive_entry_pathname(entry);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
+ const struct stat* status;
+
cout << utilname << ": ignoring " << archive_filename << endl;
- if (TH_ISREG(t))
- tar_skip_regfile(t);
+ status = archive_entry_stat(entry);
+
+ if (S_ISREG(status->st_mode))
+ archive_read_data_skip(archive);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
+ archive_entry_set_pathname(entry, const_cast<char*>
+ (real_filename.c_str()));
+
// Extract file
- if (tar_extract_file(t, const_cast<char*>(real_filename.c_str()))) {
+ if (archive_read_extract(archive, entry, 0) !=
+ ARCHIVE_OK) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
- const char* msg = strerror(errno);
+ const char* msg = archive_error_string(archive);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
+ const struct stat* status;
+
+ status = archive_entry_stat(entry);
// Directory
- if (TH_ISDIR(t))
+ if (S_ISDIR(status->st_mode))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
- if (errno == 0)
+ if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
- tar_close(t);
+ archive_read_finish(archive);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
- TAR* t;
+ struct archive* archive;
+ struct archive_entry* entry;
- if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
+ archive = archive_read_new();
+ archive_read_support_compression_all(archive);
+ archive_read_support_format_all(archive);
+
+ if (archive_read_open_filename(archive,
+ const_cast<char*>(filename.c_str()),
+ ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK)
throw runtime_error_with_errno("could not open " + filename);
- for (i = 0; !th_read(t); ++i) {
+ for (i = 0; archive_read_next_header(archive, &entry) ==
+ ARCHIVE_OK; ++i) {
+ const struct stat* status;
+
+ status = archive_entry_stat(entry);
+
// Access permissions
- if (TH_ISSYM(t)) {
+ if (S_ISLNK(status->st_mode)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
- cout << mtos(th_get_mode(t));
+ cout << mtos(archive_entry_mode(entry));
}
cout << '\t';
// User
- uid_t uid = th_get_uid(t);
+ uid_t uid = archive_entry_uid(entry);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
- gid_t gid = th_get_gid(t);
+ gid_t gid = archive_entry_gid(entry);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
- cout << '\t' << th_get_pathname(t);
+ cout << '\t' << archive_entry_pathname(entry);
// Special cases
- if (TH_ISSYM(t)) {
+ if (S_ISLNK(status->st_mode)) {
// Symlink
- cout << " -> " << th_get_linkname(t);
- } else if (TH_ISCHR(t) || TH_ISBLK(t)) {
+ cout << " -> " << archive_entry_symlink(entry);
+ } else if (S_ISCHR(status->st_mode) ||
+ S_ISBLK(status->st_mode)) {
// Device
- cout << " (" << th_get_devmajor(t) << ", " << th_get_devminor(t) << ")";
- } else if (TH_ISREG(t) && !th_get_size(t)) {
+ cout << " (" << archive_entry_rdevmajor(entry)
+ << ", " << archive_entry_rdevminor(entry)
+ << ")";
+ } else if (S_ISREG(status->st_mode) &&
+ archive_entry_size(entry) == 0) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
- if (TH_ISREG(t) && tar_skip_regfile(t))
+ if (S_ISREG(status->st_mode) &&
+ archive_read_data_skip(archive))
throw runtime_error_with_errno("could not read " + filename);
}
if (i == 0) {
- if (errno == 0)
+ if (archive_errno(archive) == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
- tar_close(t);
+ archive_read_finish(archive);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | d7fbaa09361f5b98a49ff0b3b179f2da5f574561 | Don't tar up the .git directory. | diff --git a/Makefile b/Makefile
index 0b1c5d9..5c1881c 100644
--- a/Makefile
+++ b/Makefile
@@ -1,113 +1,113 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
VERSION = 5.21
LIBTAR_VERSION = 1.2.11
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
-Ilibtar-$(LIBTAR_VERSION)/lib -Ilibtar-$(LIBTAR_VERSION)/listhash \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDFLAGS += -static -Llibtar-$(LIBTAR_VERSION)/lib -ltar -lz
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
LIBTAR = libtar-$(LIBTAR_VERSION)/lib/libtar.a
all: pkgadd pkgmk rejmerge man
$(LIBTAR):
(tar xzf libtar-$(LIBTAR_VERSION).tar.gz; \
cd libtar-$(LIBTAR_VERSION); \
patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_mem_leak.patch; \
patch -p1 < ../libtar-$(LIBTAR_VERSION)-reduce_mem_usage.patch; \
patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_linkname_overflow.patch; \
LDFLAGS="" ./configure --disable-encap --disable-encap-install; \
make)
pkgadd: $(LIBTAR) .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
rm -rf /tmp/pkgutils-$(VERSION)
mkdir -p /tmp/pkgutils-$(VERSION)
git-log > ChangeLog
cp -rf . /tmp/pkgutils-$(VERSION)
- tar -C /tmp --exclude .svn -czvf ../pkgutils-$(VERSION).tar.gz pkgutils-$(VERSION)
+ tar -C /tmp --exclude .git -czvf ../pkgutils-$(VERSION).tar.gz pkgutils-$(VERSION)
rm -rf /tmp/pkgutils-$(VERSION)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
rm -rf libtar-$(LIBTAR_VERSION)
# End of file
|
nipuL/pkgutils | 3309e1f843c1bf875965a7af8d904d29b8ba93b1 | Generate ChangeLog from "git log". | diff --git a/ChangeLog b/ChangeLog
deleted file mode 100644
index f911441..0000000
--- a/ChangeLog
+++ /dev/null
@@ -1,11 +0,0 @@
-2006-08-24 Tilman Sauerbeck (tilman at crux nu)
- * pkgadd.{h,cc}: Prepared the code for addition of the INSTALL rule
-
-2006-04-29 Simone Rota (sip at crux dot nu)
- * Optimized file type detection for stripping in pkgmk
- Thanks to Antti Nykänen
-
-2006-04-14 Tilman Sauerbeck (tilman at crux nu)
- * ChangeLog, NEWS: Moved old ChangeLog to NEWS
- * pkgmk.in: Write warnings and errors to stderr instead of stdout
- * pkgutil.cc: Use the proper sentinel in the execl() call
diff --git a/Makefile b/Makefile
index 32e0ab3..0b1c5d9 100644
--- a/Makefile
+++ b/Makefile
@@ -1,112 +1,113 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
VERSION = 5.21
LIBTAR_VERSION = 1.2.11
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
-Ilibtar-$(LIBTAR_VERSION)/lib -Ilibtar-$(LIBTAR_VERSION)/listhash \
-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDFLAGS += -static -Llibtar-$(LIBTAR_VERSION)/lib -ltar -lz
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
LIBTAR = libtar-$(LIBTAR_VERSION)/lib/libtar.a
all: pkgadd pkgmk rejmerge man
$(LIBTAR):
(tar xzf libtar-$(LIBTAR_VERSION).tar.gz; \
cd libtar-$(LIBTAR_VERSION); \
patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_mem_leak.patch; \
patch -p1 < ../libtar-$(LIBTAR_VERSION)-reduce_mem_usage.patch; \
patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_linkname_overflow.patch; \
LDFLAGS="" ./configure --disable-encap --disable-encap-install; \
make)
pkgadd: $(LIBTAR) .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
rm -rf /tmp/pkgutils-$(VERSION)
mkdir -p /tmp/pkgutils-$(VERSION)
+ git-log > ChangeLog
cp -rf . /tmp/pkgutils-$(VERSION)
tar -C /tmp --exclude .svn -czvf ../pkgutils-$(VERSION).tar.gz pkgutils-$(VERSION)
rm -rf /tmp/pkgutils-$(VERSION)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
rm -rf libtar-$(LIBTAR_VERSION)
# End of file
|
nipuL/pkgutils | 376786d8722dcb1df0690be79d3c6b8c6274cf34 | Enabled large file support. | diff --git a/Makefile b/Makefile
index 7517a2c..32e0ab3 100644
--- a/Makefile
+++ b/Makefile
@@ -1,111 +1,112 @@
#
# pkgutils
#
# Copyright (c) 2000-2005 by Per Liden <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
DESTDIR =
BINDIR = /usr/bin
MANDIR = /usr/man
ETCDIR = /etc
VERSION = 5.21
LIBTAR_VERSION = 1.2.11
CXXFLAGS += -DNDEBUG
CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
- -Ilibtar-$(LIBTAR_VERSION)/lib -Ilibtar-$(LIBTAR_VERSION)/listhash
+ -Ilibtar-$(LIBTAR_VERSION)/lib -Ilibtar-$(LIBTAR_VERSION)/listhash \
+ -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
LDFLAGS += -static -Llibtar-$(LIBTAR_VERSION)/lib -ltar -lz
OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
LIBTAR = libtar-$(LIBTAR_VERSION)/lib/libtar.a
all: pkgadd pkgmk rejmerge man
$(LIBTAR):
(tar xzf libtar-$(LIBTAR_VERSION).tar.gz; \
cd libtar-$(LIBTAR_VERSION); \
patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_mem_leak.patch; \
patch -p1 < ../libtar-$(LIBTAR_VERSION)-reduce_mem_usage.patch; \
patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_linkname_overflow.patch; \
LDFLAGS="" ./configure --disable-encap --disable-encap-install; \
make)
pkgadd: $(LIBTAR) .depend $(OBJECTS)
$(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
pkgmk: pkgmk.in
rejmerge: rejmerge.in
man: $(MANPAGES)
mantxt: man $(MANPAGES:=.txt)
%.8.txt: %.8
nroff -mandoc -c $< | col -bx > $@
%: %.in
sed -e "s/#VERSION#/$(VERSION)/" $< > $@
.depend:
$(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
ifeq (.depend,$(wildcard .depend))
include .depend
endif
.PHONY: install clean distclean dist
dist: distclean
rm -rf /tmp/pkgutils-$(VERSION)
mkdir -p /tmp/pkgutils-$(VERSION)
cp -rf . /tmp/pkgutils-$(VERSION)
tar -C /tmp --exclude .svn -czvf ../pkgutils-$(VERSION).tar.gz pkgutils-$(VERSION)
rm -rf /tmp/pkgutils-$(VERSION)
install: all
install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
clean:
rm -f .depend
rm -f $(OBJECTS)
rm -f $(MANPAGES)
rm -f $(MANPAGES:=.txt)
distclean: clean
rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
rm -rf libtar-$(LIBTAR_VERSION)
# End of file
|
nipuL/pkgutils | 14ab4111bddf38e32facfb586955d39e077d1fd5 | added documentation for the INSTALL rules | diff --git a/pkgadd.8.in b/pkgadd.8.in
index 1cfb195..564672c 100644
--- a/pkgadd.8.in
+++ b/pkgadd.8.in
@@ -1,68 +1,62 @@
.TH pkgadd 8 "" "pkgutils #VERSION#" ""
.SH NAME
pkgadd \- install software package
.SH SYNOPSIS
\fBpkgadd [options] <file>\fP
.SH DESCRIPTION
\fBpkgadd\fP is a \fIpackage management\fP utility, which installs
a software package. A \fIpackage\fP is an archive of files (.pkg.tar.gz).
.SH OPTIONS
.TP
.B "\-u, \-\-upgrade"
Upgrade/replace package with the same name as <file>.
.TP
.B "\-f, \-\-force"
Force installation, overwrite conflicting files. If the package
that is about to be installed contains files that are already
installed this option will cause all those files to be overwritten.
This option should be used with care, preferably not at all.
.TP
.B "\-r, \-\-root <path>"
Specify alternative installation root (default is "/"). This
should \fInot\fP be used as a way to install software into
e.g. /usr/local instead of /usr. Instead this should be used
if you want to install a package on a temporary mounted partition,
which is "owned" by another system. By using this option you not only
specify where the software should be installed, but you also
specify which package database to use.
.TP
.B "\-v, \-\-version"
Print version and exit.
.TP
.B "\-h, \-\-help"
Print help and exit.
.SH CONFIGURATION
-When using \fBpkgadd\fP in upgrade mode (i.e. option -u is used) the
-file \fI/etc/pkgadd.conf\fP will be read. This file can contain rules describing
-how pkgadd should behave when doing upgrades. A rule is built out of three
-fragments, \fIevent\fP, \fIpattern\fP and \fIaction\fP. The event describes
-in what kind of situation this rule applies. Currently only one type of event is
-supported, that is \fBUPGRADE\fP. The pattern is a regular expression and the action
-applicable to the \fBUPGRADE\fP event is \fBYES\fP and \fBNO\fP. More than one rule of the same
+\fBpkgadd\fP is configured by the file \fI/etc/pkgadd.conf\fP. This file can contain rules, that are built out of three fragments: \fIevent\fP, \fIpattern\fP and \fIaction\fP. The event describes in what kind of situation this rule applies. Currently there are two types of events: \fBUPGRADE\fP and \fBINSTALL\fP. \fBUPGRADE\fP rules are applied when a package is installed over an existing version, and \fBINSTALL\fP rules are applied in any case. The pattern is a regular expression. The action applicable to both the \fBUPGRADE\fP and \fBINSTALL\fP event is \fBYES\fP and \fBNO\fP. More than one rule of the same
event type is allowed, in which case the first rule will have the lowest priority and the last rule
will have the highest priority. Example:
.nf
UPGRADE ^etc/.*$ NO
UPGRADE ^var/log/.*$ NO
UPGRADE ^etc/X11/.*$ YES
UPGRADE ^etc/X11/XF86Config$ NO
.fi
The above example will cause pkgadd to never upgrade anything in /etc/ or /var/log/ (subdirectories included),
except files in /etc/X11/ (subdirectories included), unless it is the file /etc/X11/XF86Config.
-The default rule is to upgrade everything, rules in this file are exceptions to that rule.
+The default rule is to upgrade/install everything, rules in this file are exceptions to that rule.
(NOTE! A \fIpattern\fP should never contain an initial "/" since you are referring to the files in the
package, not the files on the disk.)
If pkgadd finds that a specific file should not be upgraded it will install it under \fI/var/lib/pkg/rejected/\fP.
The user is then free to examine/use/remove that file manually.
.SH FILES
.TP
.B "/etc/pkgadd.conf"
Configuration file.
.SH SEE ALSO
pkgrm(8), pkginfo(8), pkgmk(8), rejmerge(8)
.SH COPYRIGHT
pkgadd (pkgutils) is Copyright (c) 2000-2005 Per Liden and is licensed through
the GNU General Public License. Read the COPYING file for the complete license.
|
nipuL/pkgutils | e727dae97daeeb05bf4747b4c91a3461ebd695d4 | added an UPGRADE rule for /var/run/utmp. thanks to Anton Vorontsov. | diff --git a/pkgadd.conf b/pkgadd.conf
index 0442435..aa399b3 100644
--- a/pkgadd.conf
+++ b/pkgadd.conf
@@ -1,22 +1,23 @@
#
# /etc/pkgadd.conf: pkgadd(8) configuration
#
# Default rule (implicit)
#UPGRADE ^.*$ YES
UPGRADE ^etc/.*$ NO
UPGRADE ^var/log/.*$ NO
UPGRADE ^var/spool/\w*cron/.*$ NO
+UPGRADE ^var/run/utmp$ NO
UPGRADE ^etc/mail/cf/.*$ YES
UPGRADE ^etc/ports/drivers/.*$ YES
UPGRADE ^etc/X11/.*$ YES
UPGRADE ^etc/rc.*$ YES
UPGRADE ^etc/rc\.local$ NO
UPGRADE ^etc/rc\.modules$ NO
UPGRADE ^etc/rc\.conf$ NO
UPGRADE ^etc/rc\.d/net$ NO
# End of file
|
nipuL/pkgutils | 22131995295a9db9be7b461cbcefe65d8ffe9df1 | tell the user when we didn't install a file because an INSTALL rule kicked in | diff --git a/pkgutil.cc b/pkgutil.cc
index beaa74b..bdc1563 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,762 +1,764 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <libtar.h>
using __gnu_cxx::stdio_filebuf;
static tartype_t gztype = {
(openfunc_t)unistd_gzopen,
(closefunc_t)gzclose,
(readfunc_t)gzread,
(writefunc_t)gzwrite
};
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
TAR* t;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
throw runtime_error_with_errno("could not open " + filename);
for (i = 0; !th_read(t); ++i) {
result.second.files.insert(result.second.files.end(), th_get_pathname(t));
if (TH_ISREG(t) && tar_skip_regfile(t))
throw runtime_error_with_errno("could not read " + filename);
}
if (i == 0) {
if (errno == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
tar_close(t);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
TAR* t;
unsigned int i;
if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
throw runtime_error_with_errno("could not open " + filename);
for (i = 0; !th_read(t); ++i) {
string archive_filename = th_get_pathname(t);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file is filtered out via INSTALL
if (non_install_list.find(archive_filename) != non_install_list.end()) {
+ cout << utilname << ": ignoring " << archive_filename << endl;
+
if (TH_ISREG(t))
tar_skip_regfile(t);
continue;
}
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
// Extract file
if (tar_extract_file(t, const_cast<char*>(real_filename.c_str()))) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = strerror(errno);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
// Directory
if (TH_ISDIR(t))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (errno == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
tar_close(t);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
TAR* t;
if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
throw runtime_error_with_errno("could not open " + filename);
for (i = 0; !th_read(t); ++i) {
// Access permissions
if (TH_ISSYM(t)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
cout << mtos(th_get_mode(t));
}
cout << '\t';
// User
uid_t uid = th_get_uid(t);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = th_get_gid(t);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << th_get_pathname(t);
// Special cases
if (TH_ISSYM(t)) {
// Symlink
cout << " -> " << th_get_linkname(t);
} else if (TH_ISCHR(t) || TH_ISBLK(t)) {
// Device
cout << " (" << th_get_devmajor(t) << ", " << th_get_devminor(t) << ")";
} else if (TH_ISREG(t) && !th_get_size(t)) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (TH_ISREG(t) && tar_skip_regfile(t))
throw runtime_error_with_errno("could not read " + filename);
}
if (i == 0) {
if (errno == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
tar_close(t);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | 3e5b7ed9bbe9a9659486a9d4c51f3466d1e877ec | added support for INSTALL rules. based on a patch by johannes. documentation needs to be updated. | diff --git a/pkgadd.cc b/pkgadd.cc
index 8178b0a..8856851 100644
--- a/pkgadd.cc
+++ b/pkgadd.cc
@@ -1,223 +1,269 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgadd.h"
#include <fstream>
#include <iterator>
#include <cstdio>
#include <regex.h>
#include <unistd.h>
void pkgadd::run(int argc, char** argv)
{
//
// Check command line options
//
string o_root;
string o_package;
bool o_upgrade = false;
bool o_force = false;
for (int i = 1; i < argc; i++) {
string option(argv[i]);
if (option == "-r" || option == "--root") {
assert_argument(argv, argc, i);
o_root = argv[i + 1];
i++;
} else if (option == "-u" || option == "--upgrade") {
o_upgrade = true;
} else if (option == "-f" || option == "--force") {
o_force = true;
} else if (option[0] == '-' || !o_package.empty()) {
throw runtime_error("invalid option " + option);
} else {
o_package = option;
}
}
if (o_package.empty())
throw runtime_error("option missing");
//
// Check UID
//
if (getuid())
throw runtime_error("only root can install/upgrade packages");
//
// Install/upgrade package
//
{
db_lock lock(o_root, true);
db_open(o_root);
pair<string, pkginfo_t> package = pkg_open(o_package);
vector<rule_t> config_rules = read_config();
bool installed = db_find_pkg(package.first);
if (installed && !o_upgrade)
throw runtime_error("package " + package.first + " already installed (use -u to upgrade)");
else if (!installed && o_upgrade)
throw runtime_error("package " + package.first + " not previously installed (skip -u to install)");
+ set<string> non_install_files = apply_install_rules(package.first, package.second, config_rules);
set<string> conflicting_files = db_find_conflicts(package.first, package.second);
if (!conflicting_files.empty()) {
if (o_force) {
set<string> keep_list;
if (o_upgrade) // Don't remove files matching the rules in configuration
keep_list = make_keep_list(conflicting_files, config_rules);
db_rm_files(conflicting_files, keep_list); // Remove unwanted conflicts
} else {
copy(conflicting_files.begin(), conflicting_files.end(), ostream_iterator<string>(cerr, "\n"));
throw runtime_error("listed file(s) already installed (use -f to ignore and overwrite)");
}
}
set<string> keep_list;
if (o_upgrade) {
keep_list = make_keep_list(package.second.files, config_rules);
db_rm_pkg(package.first, keep_list);
}
db_add_pkg(package.first, package.second);
db_commit();
- pkg_install(o_package, keep_list);
+ pkg_install(o_package, keep_list, non_install_files);
ldconfig();
}
}
void pkgadd::print_help() const
{
cout << "usage: " << utilname << " [options] <file>" << endl
<< "options:" << endl
<< " -u, --upgrade upgrade package with the same name" << endl
<< " -f, --force force install, overwrite conflicting files" << endl
<< " -r, --root <path> specify alternative installation root" << endl
<< " -v, --version print version and exit" << endl
<< " -h, --help print help and exit" << endl;
}
vector<rule_t> pkgadd::read_config() const
{
vector<rule_t> rules;
unsigned int linecount = 0;
const string filename = root + PKGADD_CONF;
ifstream in(filename.c_str());
if (in) {
while (!in.eof()) {
string line;
getline(in, line);
linecount++;
if (!line.empty() && line[0] != '#') {
if (line.length() >= PKGADD_CONF_MAXLINE)
throw runtime_error(filename + ":" + itos(linecount) + ": line too long, aborting");
char event[PKGADD_CONF_MAXLINE];
char pattern[PKGADD_CONF_MAXLINE];
char action[PKGADD_CONF_MAXLINE];
char dummy[PKGADD_CONF_MAXLINE];
if (sscanf(line.c_str(), "%s %s %s %s", event, pattern, action, dummy) != 3)
throw runtime_error(filename + ":" + itos(linecount) + ": wrong number of arguments, aborting");
- if (!strcmp(event, "UPGRADE")) {
+ if (!strcmp(event, "UPGRADE") || !strcmp(event, "INSTALL")) {
rule_t rule;
- rule.event = UPGRADE;
+ rule.event = strcmp(event, "UPGRADE") ? INSTALL : UPGRADE;
rule.pattern = pattern;
if (!strcmp(action, "YES")) {
rule.action = true;
} else if (!strcmp(action, "NO")) {
rule.action = false;
} else
throw runtime_error(filename + ":" + itos(linecount) + ": '" +
string(action) + "' unknown action, should be YES or NO, aborting");
rules.push_back(rule);
} else
throw runtime_error(filename + ":" + itos(linecount) + ": '" +
string(event) + "' unknown event, aborting");
}
}
in.close();
}
#ifndef NDEBUG
cerr << "Configuration:" << endl;
for (vector<rule_t>::const_iterator j = rules.begin(); j != rules.end(); j++) {
cerr << "\t" << (*j).pattern << "\t" << (*j).action << endl;
}
cerr << endl;
#endif
return rules;
}
set<string> pkgadd::make_keep_list(const set<string>& files, const vector<rule_t>& rules) const
{
set<string> keep_list;
vector<rule_t> found;
find_rules(rules, UPGRADE, found);
for (set<string>::const_iterator i = files.begin(); i != files.end(); i++) {
for (vector<rule_t>::reverse_iterator j = found.rbegin(); j != found.rend(); j++) {
if (rule_applies_to_file(*j, *i)) {
if (!(*j).action)
keep_list.insert(keep_list.end(), *i);
break;
}
}
}
#ifndef NDEBUG
cerr << "Keep list:" << endl;
for (set<string>::const_iterator j = keep_list.begin(); j != keep_list.end(); j++) {
cerr << " " << (*j) << endl;
}
cerr << endl;
#endif
return keep_list;
}
+set<string> pkgadd::apply_install_rules(const string& name, pkginfo_t& info, const vector<rule_t>& rules)
+{
+ // TODO: better algo(?)
+ set<string> install_set;
+ set<string> non_install_set;
+ vector<rule_t> found;
+
+ find_rules(rules, INSTALL, found);
+
+ for (set<string>::const_iterator i = info.files.begin(); i != info.files.end(); i++) {
+ bool install_file = true;
+
+ for (vector<rule_t>::reverse_iterator j = found.rbegin(); j != found.rend(); j++) {
+ if (rule_applies_to_file(*j, *i)) {
+ install_file = (*j).action;
+ break;
+ }
+ }
+
+ if (install_file)
+ install_set.insert(install_set.end(), *i);
+ else
+ non_install_set.insert(*i);
+ }
+
+ info.files.clear();
+ info.files = install_set;
+
+#ifndef NDEBUG
+ cerr << "Install set:" << endl;
+ for (set<string>::iterator j = info.files.begin(); j != info.files.end(); j++) {
+ cerr << " " << (*j) << endl;
+ }
+ cerr << endl;
+
+ cerr << "Non-Install set:" << endl;
+ for (set<string>::iterator j = non_install_set.begin(); j != non_install_set.end(); j++) {
+ cerr << " " << (*j) << endl;
+ }
+ cerr << endl;
+#endif
+
+ return non_install_set;
+}
+
void pkgadd::find_rules(const vector<rule_t>& rules, rule_event_t event, vector<rule_t>& found) const
{
for (vector<rule_t>::const_iterator i = rules.begin(); i != rules.end(); i++)
if (i->event == event)
found.push_back(*i);
}
bool pkgadd::rule_applies_to_file(const rule_t& rule, const string& file) const
{
regex_t preg;
bool ret;
if (regcomp(&preg, rule.pattern.c_str(), REG_EXTENDED | REG_NOSUB))
throw runtime_error("error compiling regular expression '" + rule.pattern + "', aborting");
ret = !regexec(&preg, file.c_str(), 0, 0, 0);
regfree(&preg);
return ret;
}
diff --git a/pkgadd.h b/pkgadd.h
index b5b53e2..c69aab9 100644
--- a/pkgadd.h
+++ b/pkgadd.h
@@ -1,55 +1,57 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#ifndef PKGADD_H
#define PKGADD_H
#include "pkgutil.h"
#include <vector>
#include <set>
#define PKGADD_CONF "/etc/pkgadd.conf"
#define PKGADD_CONF_MAXLINE 1024
enum rule_event_t {
- UPGRADE
+ UPGRADE,
+ INSTALL
};
struct rule_t {
rule_event_t event;
string pattern;
bool action;
};
class pkgadd : public pkgutil {
public:
pkgadd() : pkgutil("pkgadd") {}
virtual void run(int argc, char** argv);
virtual void print_help() const;
private:
vector<rule_t> read_config() const;
set<string> make_keep_list(const set<string>& files, const vector<rule_t>& rules) const;
+ set<string> apply_install_rules(const string& name, pkginfo_t& info, const vector<rule_t>& rules);
void find_rules(const vector<rule_t>& rules, rule_event_t event, vector<rule_t>& found) const;
bool rule_applies_to_file(const rule_t& rule, const string& file) const;
};
#endif /* PKGADD_H */
diff --git a/pkgutil.cc b/pkgutil.cc
index 9b41c5c..beaa74b 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,754 +1,762 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <libtar.h>
using __gnu_cxx::stdio_filebuf;
static tartype_t gztype = {
(openfunc_t)unistd_gzopen,
(closefunc_t)gzclose,
(readfunc_t)gzread,
(writefunc_t)gzwrite
};
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
TAR* t;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
throw runtime_error_with_errno("could not open " + filename);
for (i = 0; !th_read(t); ++i) {
result.second.files.insert(result.second.files.end(), th_get_pathname(t));
if (TH_ISREG(t) && tar_skip_regfile(t))
throw runtime_error_with_errno("could not read " + filename);
}
if (i == 0) {
if (errno == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
tar_close(t);
return result;
}
-void pkgutil::pkg_install(const string& filename, const set<string>& keep_list) const
+void pkgutil::pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_list) const
{
TAR* t;
unsigned int i;
if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
throw runtime_error_with_errno("could not open " + filename);
for (i = 0; !th_read(t); ++i) {
string archive_filename = th_get_pathname(t);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
+ // Check if file is filtered out via INSTALL
+ if (non_install_list.find(archive_filename) != non_install_list.end()) {
+ if (TH_ISREG(t))
+ tar_skip_regfile(t);
+
+ continue;
+ }
+
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
// Extract file
if (tar_extract_file(t, const_cast<char*>(real_filename.c_str()))) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = strerror(errno);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
// Directory
if (TH_ISDIR(t))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (errno == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
tar_close(t);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
TAR* t;
if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
throw runtime_error_with_errno("could not open " + filename);
for (i = 0; !th_read(t); ++i) {
// Access permissions
if (TH_ISSYM(t)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
cout << mtos(th_get_mode(t));
}
cout << '\t';
// User
uid_t uid = th_get_uid(t);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = th_get_gid(t);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << th_get_pathname(t);
// Special cases
if (TH_ISSYM(t)) {
// Symlink
cout << " -> " << th_get_linkname(t);
} else if (TH_ISCHR(t) || TH_ISBLK(t)) {
// Device
cout << " (" << th_get_devmajor(t) << ", " << th_get_devminor(t) << ")";
} else if (TH_ISREG(t) && !th_get_size(t)) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (TH_ISREG(t) && tar_skip_regfile(t))
throw runtime_error_with_errno("could not read " + filename);
}
if (i == 0) {
if (errno == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
tar_close(t);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
diff --git a/pkgutil.h b/pkgutil.h
index 9806900..4c74de5 100644
--- a/pkgutil.h
+++ b/pkgutil.h
@@ -1,108 +1,108 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#ifndef PKGUTIL_H
#define PKGUTIL_H
#include <string>
#include <set>
#include <map>
#include <iostream>
#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <dirent.h>
#define PKG_EXT ".pkg.tar.gz"
#define PKG_DIR "var/lib/pkg"
#define PKG_DB "var/lib/pkg/db"
#define PKG_REJECTED "var/lib/pkg/rejected"
#define VERSION_DELIM '#'
#define LDCONFIG "/sbin/ldconfig"
#define LDCONFIG_CONF "/etc/ld.so.conf"
using namespace std;
class pkgutil {
public:
struct pkginfo_t {
string version;
set<string> files;
};
typedef map<string, pkginfo_t> packages_t;
explicit pkgutil(const string& name);
virtual ~pkgutil() {}
virtual void run(int argc, char** argv) = 0;
virtual void print_help() const = 0;
void print_version() const;
protected:
// Database
void db_open(const string& path);
void db_commit();
void db_add_pkg(const string& name, const pkginfo_t& info);
bool db_find_pkg(const string& name);
void db_rm_pkg(const string& name);
void db_rm_pkg(const string& name, const set<string>& keep_list);
void db_rm_files(set<string> files, const set<string>& keep_list);
set<string> db_find_conflicts(const string& name, const pkginfo_t& info);
// Tar.gz
pair<string, pkginfo_t> pkg_open(const string& filename) const;
- void pkg_install(const string& filename, const set<string>& keep_list) const;
+ void pkg_install(const string& filename, const set<string>& keep_list, const set<string>& non_install_files) const;
void pkg_footprint(string& filename) const;
void ldconfig() const;
string utilname;
packages_t packages;
string root;
};
class db_lock {
public:
db_lock(const string& root, bool exclusive);
~db_lock();
private:
DIR* dir;
};
class runtime_error_with_errno : public runtime_error {
public:
explicit runtime_error_with_errno(const string& msg) throw()
: runtime_error(msg + string(": ") + strerror(errno)) {}
};
// Utility functions
void assert_argument(char** argv, int argc, int index);
string itos(unsigned int value);
string mtos(mode_t mode);
int unistd_gzopen(char* pathname, int flags, mode_t mode);
string trim_filename(const string& filename);
bool file_exists(const string& filename);
bool file_empty(const string& filename);
bool file_equal(const string& file1, const string& file2);
bool permissions_equal(const string& file1, const string& file2);
void file_remove(const string& basedir, const string& filename);
#endif /* PKGUTIL_H */
|
nipuL/pkgutils | 1e0dfb6d09297f14827ed72e38dd48b4eb770e3f | prepared the code for the addition of the INSTALL rule | diff --git a/ChangeLog b/ChangeLog
index 4e7f542..f911441 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,7 +1,11 @@
+2006-08-24 Tilman Sauerbeck (tilman at crux nu)
+ * pkgadd.{h,cc}: Prepared the code for addition of the INSTALL rule
+
2006-04-29 Simone Rota (sip at crux dot nu)
* Optimized file type detection for stripping in pkgmk
Thanks to Antti Nykänen
+
2006-04-14 Tilman Sauerbeck (tilman at crux nu)
* ChangeLog, NEWS: Moved old ChangeLog to NEWS
* pkgmk.in: Write warnings and errors to stderr instead of stdout
* pkgutil.cc: Use the proper sentinel in the execl() call
diff --git a/pkgadd.cc b/pkgadd.cc
index dbc5641..8178b0a 100644
--- a/pkgadd.cc
+++ b/pkgadd.cc
@@ -1,206 +1,223 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgadd.h"
#include <fstream>
#include <iterator>
#include <cstdio>
#include <regex.h>
#include <unistd.h>
void pkgadd::run(int argc, char** argv)
{
//
// Check command line options
//
string o_root;
string o_package;
bool o_upgrade = false;
bool o_force = false;
for (int i = 1; i < argc; i++) {
string option(argv[i]);
if (option == "-r" || option == "--root") {
assert_argument(argv, argc, i);
o_root = argv[i + 1];
i++;
} else if (option == "-u" || option == "--upgrade") {
o_upgrade = true;
} else if (option == "-f" || option == "--force") {
o_force = true;
} else if (option[0] == '-' || !o_package.empty()) {
throw runtime_error("invalid option " + option);
} else {
o_package = option;
}
}
if (o_package.empty())
throw runtime_error("option missing");
//
// Check UID
//
if (getuid())
throw runtime_error("only root can install/upgrade packages");
//
// Install/upgrade package
//
{
db_lock lock(o_root, true);
db_open(o_root);
pair<string, pkginfo_t> package = pkg_open(o_package);
vector<rule_t> config_rules = read_config();
bool installed = db_find_pkg(package.first);
if (installed && !o_upgrade)
throw runtime_error("package " + package.first + " already installed (use -u to upgrade)");
else if (!installed && o_upgrade)
throw runtime_error("package " + package.first + " not previously installed (skip -u to install)");
set<string> conflicting_files = db_find_conflicts(package.first, package.second);
if (!conflicting_files.empty()) {
if (o_force) {
set<string> keep_list;
if (o_upgrade) // Don't remove files matching the rules in configuration
keep_list = make_keep_list(conflicting_files, config_rules);
db_rm_files(conflicting_files, keep_list); // Remove unwanted conflicts
} else {
copy(conflicting_files.begin(), conflicting_files.end(), ostream_iterator<string>(cerr, "\n"));
throw runtime_error("listed file(s) already installed (use -f to ignore and overwrite)");
}
}
set<string> keep_list;
if (o_upgrade) {
keep_list = make_keep_list(package.second.files, config_rules);
db_rm_pkg(package.first, keep_list);
}
db_add_pkg(package.first, package.second);
db_commit();
pkg_install(o_package, keep_list);
ldconfig();
}
}
void pkgadd::print_help() const
{
cout << "usage: " << utilname << " [options] <file>" << endl
<< "options:" << endl
<< " -u, --upgrade upgrade package with the same name" << endl
<< " -f, --force force install, overwrite conflicting files" << endl
<< " -r, --root <path> specify alternative installation root" << endl
<< " -v, --version print version and exit" << endl
<< " -h, --help print help and exit" << endl;
}
vector<rule_t> pkgadd::read_config() const
{
vector<rule_t> rules;
unsigned int linecount = 0;
const string filename = root + PKGADD_CONF;
ifstream in(filename.c_str());
if (in) {
while (!in.eof()) {
string line;
getline(in, line);
linecount++;
if (!line.empty() && line[0] != '#') {
if (line.length() >= PKGADD_CONF_MAXLINE)
throw runtime_error(filename + ":" + itos(linecount) + ": line too long, aborting");
char event[PKGADD_CONF_MAXLINE];
char pattern[PKGADD_CONF_MAXLINE];
char action[PKGADD_CONF_MAXLINE];
char dummy[PKGADD_CONF_MAXLINE];
if (sscanf(line.c_str(), "%s %s %s %s", event, pattern, action, dummy) != 3)
throw runtime_error(filename + ":" + itos(linecount) + ": wrong number of arguments, aborting");
if (!strcmp(event, "UPGRADE")) {
rule_t rule;
- rule.event = rule_t::UPGRADE;
+ rule.event = UPGRADE;
rule.pattern = pattern;
if (!strcmp(action, "YES")) {
rule.action = true;
} else if (!strcmp(action, "NO")) {
rule.action = false;
} else
throw runtime_error(filename + ":" + itos(linecount) + ": '" +
string(action) + "' unknown action, should be YES or NO, aborting");
rules.push_back(rule);
} else
throw runtime_error(filename + ":" + itos(linecount) + ": '" +
string(event) + "' unknown event, aborting");
}
}
in.close();
}
#ifndef NDEBUG
cerr << "Configuration:" << endl;
for (vector<rule_t>::const_iterator j = rules.begin(); j != rules.end(); j++) {
cerr << "\t" << (*j).pattern << "\t" << (*j).action << endl;
}
cerr << endl;
#endif
return rules;
}
set<string> pkgadd::make_keep_list(const set<string>& files, const vector<rule_t>& rules) const
{
set<string> keep_list;
+ vector<rule_t> found;
+
+ find_rules(rules, UPGRADE, found);
for (set<string>::const_iterator i = files.begin(); i != files.end(); i++) {
- for (vector<rule_t>::const_reverse_iterator j = rules.rbegin(); j != rules.rend(); j++) {
- if ((*j).event == rule_t::UPGRADE) {
- regex_t preg;
- if (regcomp(&preg, (*j).pattern.c_str(), REG_EXTENDED | REG_NOSUB))
- throw runtime_error("error compiling regular expression '" + (*j).pattern + "', aborting");
-
- if (!regexec(&preg, (*i).c_str(), 0, 0, 0)) {
- if (!(*j).action)
- keep_list.insert(keep_list.end(), *i);
- regfree(&preg);
- break;
- }
- regfree(&preg);
+ for (vector<rule_t>::reverse_iterator j = found.rbegin(); j != found.rend(); j++) {
+ if (rule_applies_to_file(*j, *i)) {
+ if (!(*j).action)
+ keep_list.insert(keep_list.end(), *i);
+
+ break;
}
}
}
#ifndef NDEBUG
cerr << "Keep list:" << endl;
for (set<string>::const_iterator j = keep_list.begin(); j != keep_list.end(); j++) {
cerr << " " << (*j) << endl;
}
cerr << endl;
#endif
return keep_list;
}
+
+void pkgadd::find_rules(const vector<rule_t>& rules, rule_event_t event, vector<rule_t>& found) const
+{
+ for (vector<rule_t>::const_iterator i = rules.begin(); i != rules.end(); i++)
+ if (i->event == event)
+ found.push_back(*i);
+}
+
+bool pkgadd::rule_applies_to_file(const rule_t& rule, const string& file) const
+{
+ regex_t preg;
+ bool ret;
+
+ if (regcomp(&preg, rule.pattern.c_str(), REG_EXTENDED | REG_NOSUB))
+ throw runtime_error("error compiling regular expression '" + rule.pattern + "', aborting");
+
+ ret = !regexec(&preg, file.c_str(), 0, 0, 0);
+ regfree(&preg);
+
+ return ret;
+}
diff --git a/pkgadd.h b/pkgadd.h
index 46e0f1b..b5b53e2 100644
--- a/pkgadd.h
+++ b/pkgadd.h
@@ -1,49 +1,55 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#ifndef PKGADD_H
#define PKGADD_H
#include "pkgutil.h"
#include <vector>
#include <set>
#define PKGADD_CONF "/etc/pkgadd.conf"
#define PKGADD_CONF_MAXLINE 1024
+enum rule_event_t {
+ UPGRADE
+};
+
struct rule_t {
- enum { UPGRADE } event;
+ rule_event_t event;
string pattern;
bool action;
};
class pkgadd : public pkgutil {
public:
pkgadd() : pkgutil("pkgadd") {}
virtual void run(int argc, char** argv);
virtual void print_help() const;
private:
vector<rule_t> read_config() const;
set<string> make_keep_list(const set<string>& files, const vector<rule_t>& rules) const;
+ void find_rules(const vector<rule_t>& rules, rule_event_t event, vector<rule_t>& found) const;
+ bool rule_applies_to_file(const rule_t& rule, const string& file) const;
};
#endif /* PKGADD_H */
|
nipuL/pkgutils | b0bbde50af5aba136af13bb0f5e3869e101914df | pkgmk: optimize file detection for stripping. Thanks to aon and mark | diff --git a/ChangeLog b/ChangeLog
index 47361a8..4e7f542 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,4 +1,7 @@
+2006-04-29 Simone Rota (sip at crux dot nu)
+ * Optimized file type detection for stripping in pkgmk
+ Thanks to Antti Nykänen
2006-04-14 Tilman Sauerbeck (tilman at crux nu)
* ChangeLog, NEWS: Moved old ChangeLog to NEWS
* pkgmk.in: Write warnings and errors to stderr instead of stdout
* pkgutil.cc: Use the proper sentinel in the execl() call
diff --git a/pkgmk.in b/pkgmk.in
index 51fd8f6..bfa1701 100755
--- a/pkgmk.in
+++ b/pkgmk.in
@@ -1,653 +1,656 @@
#!/bin/bash
#
# pkgutils
#
# Copyright (c) 2000-2005 Per Liden
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
info() {
echo "=======> $1"
}
warning() {
info "WARNING: $1" >&2
}
error() {
info "ERROR: $1" >&2
}
get_filename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
if [ "$FILE" != "$1" ]; then
FILE="$PKGMK_SOURCE_DIR/$FILE"
fi
echo $FILE
}
check_pkgfile() {
if [ ! "$name" ]; then
error "Variable 'name' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$version" ]; then
error "Variable 'version' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$release" ]; then
error "Variable 'release' not specified in $PKGMK_PKGFILE."
exit 1
elif [ "`type -t build`" != "function" ]; then
error "Function 'build' not specified in $PKGMK_PKGFILE."
exit 1
fi
}
check_directory() {
if [ ! -d $1 ]; then
error "Directory '$1' does not exist."
exit 1
elif [ ! -w $1 ]; then
error "Directory '$1' not writable."
exit 1
elif [ ! -x $1 ] || [ ! -r $1 ]; then
error "Directory '$1' not readable."
exit 1
fi
}
download_file() {
info "Downloading '$1'."
if [ ! "`type -p wget`" ]; then
error "Command 'wget' not found."
exit 1
fi
LOCAL_FILENAME=`get_filename $1`
LOCAL_FILENAME_PARTIAL="$LOCAL_FILENAME.partial"
DOWNLOAD_CMD="--passive-ftp --no-directories --tries=3 --waitretry=3 \
--directory-prefix=$PKGMK_SOURCE_DIR --output-document=$LOCAL_FILENAME_PARTIAL $1"
if [ -f "$LOCAL_FILENAME_PARTIAL" ]; then
info "Partial download found, trying to resume"
RESUME_CMD="-c"
fi
while true; do
wget $RESUME_CMD $DOWNLOAD_CMD
error=$?
if [ $error != 0 ] && [ "$RESUME_CMD" ]; then
info "Partial download failed, restarting"
rm -f "$LOCAL_FILENAME_PARTIAL"
RESUME_CMD=""
else
break
fi
done
if [ $error != 0 ]; then
error "Downloading '$1' failed."
exit 1
fi
mv -f "$LOCAL_FILENAME_PARTIAL" "$LOCAL_FILENAME"
}
download_source() {
local FILE LOCAL_FILENAME
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ ! -e $LOCAL_FILENAME ]; then
if [ "$LOCAL_FILENAME" = "$FILE" ]; then
error "Source file '$LOCAL_FILENAME' not found (can not be downloaded, URL not specified)."
exit 1
else
if [ "$PKGMK_DOWNLOAD" = "yes" ]; then
download_file $FILE
else
error "Source file '$LOCAL_FILENAME' not found (use option -d to download)."
exit 1
fi
fi
fi
done
}
unpack_source() {
local FILE LOCAL_FILENAME COMMAND
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
case $LOCAL_FILENAME in
*.tar.gz|*.tar.Z|*.tgz)
COMMAND="tar -C $SRC --use-compress-program=gzip -xf $LOCAL_FILENAME" ;;
*.tar.bz2)
COMMAND="tar -C $SRC --use-compress-program=bzip2 -xf $LOCAL_FILENAME" ;;
*.zip)
COMMAND="unzip -qq -o -d $SRC $LOCAL_FILENAME" ;;
*)
COMMAND="cp $LOCAL_FILENAME $SRC" ;;
esac
echo "$COMMAND"
$COMMAND
if [ $? != 0 ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
error "Building '$TARGET' failed."
exit 1
fi
done
}
make_md5sum() {
local FILE LOCAL_FILENAMES
if [ "$source" ]; then
for FILE in ${source[@]}; do
LOCAL_FILENAMES="$LOCAL_FILENAMES `get_filename $FILE`"
done
md5sum $LOCAL_FILENAMES | sed -e 's| .*/| |' | sort -k 2
fi
}
make_footprint() {
pkginfo --footprint $TARGET | \
sed "s|\tlib/modules/`uname -r`/|\tlib/modules/<kernel-version>/|g" | \
sort -k 3
}
check_md5sum() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $PKGMK_MD5SUM ]; then
make_md5sum > $FILE.md5sum
sort -k 2 $PKGMK_MD5SUM > $FILE.md5sum.orig
diff -w -t -U 0 $FILE.md5sum.orig $FILE.md5sum | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.md5sum.diff
if [ -s $FILE.md5sum.diff ]; then
error "Md5sum mismatch found:"
cat $FILE.md5sum.diff >&2
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
error "Md5sum not ok."
exit 1
fi
error "Building '$TARGET' failed."
exit 1
fi
else
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum not found."
exit 1
fi
warning "Md5sum not found, creating new."
make_md5sum > $PKGMK_MD5SUM
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum ok."
exit 0
fi
}
strip_files() {
local FILE FILTER
cd $PKG
if [ -f $PKGMK_ROOT/$PKGMK_NOSTRIP ]; then
FILTER="grep -v -f $PKGMK_ROOT/$PKGMK_NOSTRIP"
else
FILTER="cat"
fi
find . -type f -printf "%P\n" | $FILTER | while read FILE; do
- if file -b "$FILE" | grep '^.*ELF.*executable.*not stripped$' &> /dev/null; then
+ case $(file -b "$FILE") in
+ *ELF*executable*not\ stripped)
strip --strip-all "$FILE"
- elif file -b "$FILE" | grep '^.*ELF.*shared object.*not stripped$' &> /dev/null; then
+ ;;
+ *ELF*shared\ object*not\ stripped)
strip --strip-unneeded "$FILE"
- elif file -b "$FILE" | grep '^current ar archive$' &> /dev/null; then
+ ;;
+ current\ ar\ archive)
strip --strip-debug "$FILE"
- fi
+ esac
done
}
compress_manpages() {
local FILE DIR TARGET
cd $PKG
find . -type f -path "*/man/man*/*" | while read FILE; do
if [ "$FILE" = "${FILE%%.gz}" ]; then
gzip -9 "$FILE"
fi
done
find . -type l -path "*/man/man*/*" | while read FILE; do
TARGET=`readlink -n "$FILE"`
TARGET="${TARGET##*/}"
TARGET="${TARGET%%.gz}.gz"
rm -f "$FILE"
FILE="${FILE%%.gz}.gz"
DIR=`dirname "$FILE"`
if [ -e "$DIR/$TARGET" ]; then
ln -sf "$TARGET" "$FILE"
fi
done
}
check_footprint() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $TARGET ]; then
make_footprint > $FILE.footprint
if [ -f $PKGMK_FOOTPRINT ]; then
sort -k 3 $PKGMK_FOOTPRINT > $FILE.footprint.orig
diff -w -t -U 0 $FILE.footprint.orig $FILE.footprint | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.footprint.diff
if [ -s $FILE.footprint.diff ]; then
error "Footprint mismatch found:"
cat $FILE.footprint.diff >&2
BUILD_SUCCESSFUL="no"
fi
else
warning "Footprint not found, creating new."
mv $FILE.footprint $PKGMK_FOOTPRINT
fi
else
error "Package '$TARGET' was not found."
BUILD_SUCCESSFUL="no"
fi
}
build_package() {
local BUILD_SUCCESSFUL="no"
export PKG="$PKGMK_WORK_DIR/pkg"
export SRC="$PKGMK_WORK_DIR/src"
umask 022
cd $PKGMK_ROOT
rm -rf $PKGMK_WORK_DIR
mkdir -p $SRC $PKG
if [ "$PKGMK_IGNORE_MD5SUM" = "no" ]; then
check_md5sum
fi
if [ "$UID" != "0" ]; then
warning "Packages should be built as root."
fi
info "Building '$TARGET'."
unpack_source
cd $SRC
(set -e -x ; build)
if [ $? = 0 ]; then
if [ "$PKGMK_NO_STRIP" = "no" ]; then
strip_files
fi
compress_manpages
cd $PKG
info "Build result:"
tar czvvf $TARGET *
if [ $? = 0 ]; then
BUILD_SUCCESSFUL="yes"
if [ "$PKGMK_IGNORE_FOOTPRINT" = "yes" ]; then
warning "Footprint ignored."
else
check_footprint
fi
fi
fi
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$BUILD_SUCCESSFUL" = "yes" ]; then
info "Building '$TARGET' succeeded."
else
if [ -f $TARGET ]; then
touch -r $PKGMK_ROOT/$PKGMK_PKGFILE $TARGET &> /dev/null
fi
error "Building '$TARGET' failed."
exit 1
fi
}
install_package() {
local COMMAND
info "Installing '$TARGET'."
if [ "$PKGMK_INSTALL" = "install" ]; then
COMMAND="pkgadd $TARGET"
else
COMMAND="pkgadd -u $TARGET"
fi
cd $PKGMK_ROOT
echo "$COMMAND"
$COMMAND
if [ $? = 0 ]; then
info "Installing '$TARGET' succeeded."
else
error "Installing '$TARGET' failed."
exit 1
fi
}
recursive() {
local ARGS FILE DIR
ARGS=`echo "$@" | sed -e "s/--recursive//g" -e "s/-r//g"`
for FILE in `find $PKGMK_ROOT -name $PKGMK_PKGFILE | sort`; do
DIR="`dirname $FILE`/"
if [ -d $DIR ]; then
info "Entering directory '$DIR'."
(cd $DIR && $PKGMK_COMMAND $ARGS)
info "Leaving directory '$DIR'."
fi
done
}
clean() {
local FILE LOCAL_FILENAME
if [ -f $TARGET ]; then
info "Removing $TARGET"
rm -f $TARGET
fi
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ -e $LOCAL_FILENAME ] && [ "$LOCAL_FILENAME" != "$FILE" ]; then
info "Removing $LOCAL_FILENAME"
rm -f $LOCAL_FILENAME
fi
done
}
update_footprint() {
if [ ! -f $TARGET ]; then
error "Unable to update footprint. File '$TARGET' not found."
exit 1
fi
make_footprint > $PKGMK_FOOTPRINT
touch $TARGET
info "Footprint updated."
}
build_needed() {
local FILE RESULT
RESULT="yes"
if [ -f $TARGET ]; then
RESULT="no"
for FILE in $PKGMK_PKGFILE ${source[@]}; do
FILE=`get_filename $FILE`
if [ ! -e $FILE ] || [ ! $TARGET -nt $FILE ]; then
RESULT="yes"
break
fi
done
fi
echo $RESULT
}
interrupted() {
echo ""
error "Interrupted."
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
exit 1
}
print_help() {
echo "usage: `basename $PKGMK_COMMAND` [options]"
echo "options:"
echo " -i, --install build and install package"
echo " -u, --upgrade build and install package (as upgrade)"
echo " -r, --recursive search for and build packages recursively"
echo " -d, --download download missing source file(s)"
echo " -do, --download-only do not build, only download missing source file(s)"
echo " -utd, --up-to-date do not build, only check if package is up to date"
echo " -uf, --update-footprint update footprint using result from last build"
echo " -if, --ignore-footprint build package without checking footprint"
echo " -um, --update-md5sum update md5sum"
echo " -im, --ignore-md5sum build package without checking md5sum"
echo " -cm, --check-md5sum do not build, only check md5sum"
echo " -ns, --no-strip do not strip executable binaries or libraries"
echo " -f, --force build package even if it appears to be up to date"
echo " -c, --clean remove package and downloaded files"
echo " -kw, --keep-work keep temporary working directory"
echo " -cf, --config-file <file> use alternative configuration file"
echo " -v, --version print version and exit "
echo " -h, --help print help and exit"
}
parse_options() {
while [ "$1" ]; do
case $1 in
-i|--install)
PKGMK_INSTALL="install" ;;
-u|--upgrade)
PKGMK_INSTALL="upgrade" ;;
-r|--recursive)
PKGMK_RECURSIVE="yes" ;;
-d|--download)
PKGMK_DOWNLOAD="yes" ;;
-do|--download-only)
PKGMK_DOWNLOAD="yes"
PKGMK_DOWNLOAD_ONLY="yes" ;;
-utd|--up-to-date)
PKGMK_UP_TO_DATE="yes" ;;
-uf|--update-footprint)
PKGMK_UPDATE_FOOTPRINT="yes" ;;
-if|--ignore-footprint)
PKGMK_IGNORE_FOOTPRINT="yes" ;;
-um|--update-md5sum)
PKGMK_UPDATE_MD5SUM="yes" ;;
-im|--ignore-md5sum)
PKGMK_IGNORE_MD5SUM="yes" ;;
-cm|--check-md5sum)
PKGMK_CHECK_MD5SUM="yes" ;;
-ns|--no-strip)
PKGMK_NO_STRIP="yes" ;;
-f|--force)
PKGMK_FORCE="yes" ;;
-c|--clean)
PKGMK_CLEAN="yes" ;;
-kw|--keep-work)
PKGMK_KEEP_WORK="yes" ;;
-cf|--config-file)
if [ ! "$2" ]; then
echo "`basename $PKGMK_COMMAND`: option $1 requires an argument"
exit 1
fi
PKGMK_CONFFILE="$2"
shift ;;
-v|--version)
echo "`basename $PKGMK_COMMAND` (pkgutils) $PKGMK_VERSION"
exit 0 ;;
-h|--help)
print_help
exit 0 ;;
*)
echo "`basename $PKGMK_COMMAND`: invalid option $1"
exit 1 ;;
esac
shift
done
}
main() {
local FILE TARGET
parse_options "$@"
if [ "$PKGMK_RECURSIVE" = "yes" ]; then
recursive "$@"
exit 0
fi
for FILE in $PKGMK_PKGFILE $PKGMK_CONFFILE; do
if [ ! -f $FILE ]; then
error "File '$FILE' not found."
exit 1
fi
. $FILE
done
check_directory "$PKGMK_SOURCE_DIR"
check_directory "$PKGMK_PACKAGE_DIR"
check_directory "`dirname $PKGMK_WORK_DIR`"
check_pkgfile
TARGET="$PKGMK_PACKAGE_DIR/$name#$version-$release.pkg.tar.gz"
if [ "$PKGMK_CLEAN" = "yes" ]; then
clean
exit 0
fi
if [ "$PKGMK_UPDATE_FOOTPRINT" = "yes" ]; then
update_footprint
exit 0
fi
if [ "$PKGMK_UPDATE_MD5SUM" = "yes" ]; then
download_source
make_md5sum > $PKGMK_MD5SUM
info "Md5sum updated."
exit 0
fi
if [ "$PKGMK_DOWNLOAD_ONLY" = "yes" ]; then
download_source
exit 0
fi
if [ "$PKGMK_UP_TO_DATE" = "yes" ]; then
if [ "`build_needed`" = "yes" ]; then
info "Package '$TARGET' is not up to date."
else
info "Package '$TARGET' is up to date."
fi
exit 0
fi
if [ "`build_needed`" = "no" ] && [ "$PKGMK_FORCE" = "no" ] && [ "$PKGMK_CHECK_MD5SUM" = "no" ]; then
info "Package '$TARGET' is up to date."
else
download_source
build_package
fi
if [ "$PKGMK_INSTALL" != "no" ]; then
install_package
fi
exit 0
}
trap "interrupted" SIGHUP SIGINT SIGQUIT SIGTERM
export LC_ALL=POSIX
readonly PKGMK_VERSION="#VERSION#"
readonly PKGMK_COMMAND="$0"
readonly PKGMK_ROOT="$PWD"
PKGMK_CONFFILE="/etc/pkgmk.conf"
PKGMK_PKGFILE="Pkgfile"
PKGMK_FOOTPRINT=".footprint"
PKGMK_MD5SUM=".md5sum"
PKGMK_NOSTRIP=".nostrip"
PKGMK_SOURCE_DIR="$PWD"
PKGMK_PACKAGE_DIR="$PWD"
PKGMK_WORK_DIR="$PWD/work"
PKGMK_INSTALL="no"
PKGMK_RECURSIVE="no"
PKGMK_DOWNLOAD="no"
PKGMK_DOWNLOAD_ONLY="no"
PKGMK_UP_TO_DATE="no"
PKGMK_UPDATE_FOOTPRINT="no"
PKGMK_IGNORE_FOOTPRINT="no"
PKGMK_FORCE="no"
PKGMK_KEEP_WORK="no"
PKGMK_UPDATE_MD5SUM="no"
PKGMK_IGNORE_MD5SUM="no"
PKGMK_CHECK_MD5SUM="no"
PKGMK_NO_STRIP="no"
PKGMK_CLEAN="no"
main "$@"
# End of file
|
nipuL/pkgutils | 4943d62183b446fb9316e1393d115425ac305292 | added an UPGRADE rule for crontabs | diff --git a/pkgadd.conf b/pkgadd.conf
index 642e09b..0442435 100644
--- a/pkgadd.conf
+++ b/pkgadd.conf
@@ -1,21 +1,22 @@
#
# /etc/pkgadd.conf: pkgadd(8) configuration
#
# Default rule (implicit)
#UPGRADE ^.*$ YES
UPGRADE ^etc/.*$ NO
UPGRADE ^var/log/.*$ NO
+UPGRADE ^var/spool/\w*cron/.*$ NO
UPGRADE ^etc/mail/cf/.*$ YES
UPGRADE ^etc/ports/drivers/.*$ YES
UPGRADE ^etc/X11/.*$ YES
UPGRADE ^etc/rc.*$ YES
UPGRADE ^etc/rc\.local$ NO
UPGRADE ^etc/rc\.modules$ NO
UPGRADE ^etc/rc\.conf$ NO
UPGRADE ^etc/rc\.d/net$ NO
# End of file
|
nipuL/pkgutils | 5401bd4576520efbe50d5f6eda4cc70788823879 | use the proper sentinel in the execl() call | diff --git a/ChangeLog b/ChangeLog
index cdd6f1c..47361a8 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,4 @@
2006-04-14 Tilman Sauerbeck (tilman at crux nu)
* ChangeLog, NEWS: Moved old ChangeLog to NEWS
* pkgmk.in: Write warnings and errors to stderr instead of stdout
+ * pkgutil.cc: Use the proper sentinel in the execl() call
diff --git a/pkgutil.cc b/pkgutil.cc
index 571dd6e..9b41c5c 100644
--- a/pkgutil.cc
+++ b/pkgutil.cc
@@ -1,754 +1,754 @@
//
// pkgutils
//
// Copyright (c) 2000-2005 Per Liden
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
#include "pkgutil.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <ext/stdio_filebuf.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <zlib.h>
#include <libgen.h>
#include <libtar.h>
using __gnu_cxx::stdio_filebuf;
static tartype_t gztype = {
(openfunc_t)unistd_gzopen,
(closefunc_t)gzclose,
(readfunc_t)gzread,
(writefunc_t)gzwrite
};
pkgutil::pkgutil(const string& name)
: utilname(name)
{
// Ignore signals
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
}
void pkgutil::db_open(const string& path)
{
// Read database
root = trim_filename(path + "/");
const string filename = root + PKG_DB;
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
throw runtime_error_with_errno("could not open " + filename);
stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
istream in(&filebuf);
if (!in)
throw runtime_error_with_errno("could not read " + filename);
while (!in.eof()) {
// Read record
string name;
pkginfo_t info;
getline(in, name);
getline(in, info.version);
for (;;) {
string file;
getline(in, file);
if (file.empty())
break; // End of record
info.files.insert(info.files.end(), file);
}
if (!info.files.empty())
packages[name] = info;
}
#ifndef NDEBUG
cerr << packages.size() << " packages found in database" << endl;
#endif
}
void pkgutil::db_commit()
{
const string dbfilename = root + PKG_DB;
const string dbfilename_new = dbfilename + ".incomplete_transaction";
const string dbfilename_bak = dbfilename + ".backup";
// Remove failed transaction (if it exists)
if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_new);
// Write new database
int fd_new = creat(dbfilename_new.c_str(), 0444);
if (fd_new == -1)
throw runtime_error_with_errno("could not create " + dbfilename_new);
stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
ostream db_new(&filebuf_new);
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (!i->second.files.empty()) {
db_new << i->first << "\n";
db_new << i->second.version << "\n";
copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
db_new << "\n";
}
}
db_new.flush();
// Make sure the new database was successfully written
if (!db_new)
throw runtime_error("could not write " + dbfilename_new);
// Synchronize file to disk
if (fsync(fd_new) == -1)
throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
// Relink database backup
if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
throw runtime_error_with_errno("could not remove " + dbfilename_bak);
if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
throw runtime_error_with_errno("could not create " + dbfilename_bak);
// Move new database into place
if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
#ifndef NDEBUG
cerr << packages.size() << " packages written to database" << endl;
#endif
}
void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
{
packages[name] = info;
}
bool pkgutil::db_find_pkg(const string& name)
{
return (packages.find(name) != packages.end());
}
void pkgutil::db_rm_pkg(const string& name)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
{
set<string> files = packages[name].files;
packages.erase(name);
#ifndef NDEBUG
cerr << "Removing package phase 1 (all files in package):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files that still have references
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
files.erase(*j);
#ifndef NDEBUG
cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
{
// Remove all references
for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
i->second.files.erase(*j);
#ifndef NDEBUG
cerr << "Removing files:" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Don't delete files found in the keep list
for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
files.erase(*i);
// Delete the files
for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && remove(filename.c_str()) == -1) {
if (errno == ENOTEMPTY)
continue;
const char* msg = strerror(errno);
cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
}
}
}
set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
{
set<string> files;
// Find conflicting files in database
for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
if (i->first != name) {
set_intersection(info.files.begin(), info.files.end(),
i->second.files.begin(), i->second.files.end(),
inserter(files, files.end()));
}
}
#ifndef NDEBUG
cerr << "Conflicts phase 1 (conflicts in database):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Find conflicting files in filesystem
for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
const string filename = root + *i;
if (file_exists(filename) && files.find(*i) == files.end())
files.insert(files.end(), *i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// Exclude directories
set<string> tmp = files;
for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
if ((*i)[i->length() - 1] == '/')
files.erase(*i);
}
#ifndef NDEBUG
cerr << "Conflicts phase 3 (directories excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
// If this is an upgrade, remove files already owned by this package
if (packages.find(name) != packages.end()) {
for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
files.erase(*i);
#ifndef NDEBUG
cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
cerr << endl;
#endif
}
return files;
}
pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
{
pair<string, pkginfo_t> result;
unsigned int i;
TAR* t;
// Extract name and version from filename
string basename(filename, filename.rfind('/') + 1);
string name(basename, 0, basename.find(VERSION_DELIM));
string version(basename, 0, basename.rfind(PKG_EXT));
version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
if (name.empty() || version.empty())
throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
result.first = name;
result.second.version = version;
if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
throw runtime_error_with_errno("could not open " + filename);
for (i = 0; !th_read(t); ++i) {
result.second.files.insert(result.second.files.end(), th_get_pathname(t));
if (TH_ISREG(t) && tar_skip_regfile(t))
throw runtime_error_with_errno("could not read " + filename);
}
if (i == 0) {
if (errno == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
tar_close(t);
return result;
}
void pkgutil::pkg_install(const string& filename, const set<string>& keep_list) const
{
TAR* t;
unsigned int i;
if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
throw runtime_error_with_errno("could not open " + filename);
for (i = 0; !th_read(t); ++i) {
string archive_filename = th_get_pathname(t);
string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
string original_filename = trim_filename(root + string("/") + archive_filename);
string real_filename = original_filename;
// Check if file should be rejected
if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
real_filename = trim_filename(reject_dir + string("/") + archive_filename);
// Extract file
if (tar_extract_file(t, const_cast<char*>(real_filename.c_str()))) {
// If a file fails to install we just print an error message and
// continue trying to install the rest of the package.
const char* msg = strerror(errno);
cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
continue;
}
// Check rejected file
if (real_filename != original_filename) {
bool remove_file = false;
// Directory
if (TH_ISDIR(t))
remove_file = permissions_equal(real_filename, original_filename);
// Other files
else
remove_file = permissions_equal(real_filename, original_filename) &&
(file_empty(real_filename) || file_equal(real_filename, original_filename));
// Remove rejected file or signal about its existence
if (remove_file)
file_remove(reject_dir, real_filename);
else
cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
}
}
if (i == 0) {
if (errno == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
tar_close(t);
}
void pkgutil::ldconfig() const
{
// Only execute ldconfig if /etc/ld.so.conf exists
if (file_exists(root + LDCONFIG_CONF)) {
pid_t pid = fork();
if (pid == -1)
throw runtime_error_with_errno("fork() failed");
if (pid == 0) {
- execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), 0);
+ execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), (char *) 0);
const char* msg = strerror(errno);
cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
exit(EXIT_FAILURE);
} else {
if (waitpid(pid, 0, 0) == -1)
throw runtime_error_with_errno("waitpid() failed");
}
}
}
void pkgutil::pkg_footprint(string& filename) const
{
unsigned int i;
TAR* t;
if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
throw runtime_error_with_errno("could not open " + filename);
for (i = 0; !th_read(t); ++i) {
// Access permissions
if (TH_ISSYM(t)) {
// Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
// To avoid getting different footprints we always use "lrwxrwxrwx".
cout << "lrwxrwxrwx";
} else {
cout << mtos(th_get_mode(t));
}
cout << '\t';
// User
uid_t uid = th_get_uid(t);
struct passwd* pw = getpwuid(uid);
if (pw)
cout << pw->pw_name;
else
cout << uid;
cout << '/';
// Group
gid_t gid = th_get_gid(t);
struct group* gr = getgrgid(gid);
if (gr)
cout << gr->gr_name;
else
cout << gid;
// Filename
cout << '\t' << th_get_pathname(t);
// Special cases
if (TH_ISSYM(t)) {
// Symlink
cout << " -> " << th_get_linkname(t);
} else if (TH_ISCHR(t) || TH_ISBLK(t)) {
// Device
cout << " (" << th_get_devmajor(t) << ", " << th_get_devminor(t) << ")";
} else if (TH_ISREG(t) && !th_get_size(t)) {
// Empty regular file
cout << " (EMPTY)";
}
cout << '\n';
if (TH_ISREG(t) && tar_skip_regfile(t))
throw runtime_error_with_errno("could not read " + filename);
}
if (i == 0) {
if (errno == 0)
throw runtime_error("empty package");
else
throw runtime_error("could not read " + filename);
}
tar_close(t);
}
void pkgutil::print_version() const
{
cout << utilname << " (pkgutils) " << VERSION << endl;
}
db_lock::db_lock(const string& root, bool exclusive)
: dir(0)
{
const string dirname = trim_filename(root + string("/") + PKG_DIR);
if (!(dir = opendir(dirname.c_str())))
throw runtime_error_with_errno("could not read directory " + dirname);
if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
if (errno == EWOULDBLOCK)
throw runtime_error("package database is currently locked by another process");
else
throw runtime_error_with_errno("could not lock directory " + dirname);
}
}
db_lock::~db_lock()
{
if (dir) {
flock(dirfd(dir), LOCK_UN);
closedir(dir);
}
}
void assert_argument(char** argv, int argc, int index)
{
if (argc - 1 < index + 1)
throw runtime_error("option " + string(argv[index]) + " requires an argument");
}
string itos(unsigned int value)
{
static char buf[20];
sprintf(buf, "%u", value);
return buf;
}
string mtos(mode_t mode)
{
string s;
// File type
switch (mode & S_IFMT) {
case S_IFREG: s += '-'; break; // Regular
case S_IFDIR: s += 'd'; break; // Directory
case S_IFLNK: s += 'l'; break; // Symbolic link
case S_IFCHR: s += 'c'; break; // Character special
case S_IFBLK: s += 'b'; break; // Block special
case S_IFSOCK: s += 's'; break; // Socket
case S_IFIFO: s += 'p'; break; // Fifo
default: s += '?'; break; // Unknown
}
// User permissions
s += (mode & S_IRUSR) ? 'r' : '-';
s += (mode & S_IWUSR) ? 'w' : '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case S_IXUSR: s += 'x'; break;
case S_ISUID: s += 'S'; break;
case S_IXUSR | S_ISUID: s += 's'; break;
default: s += '-'; break;
}
// Group permissions
s += (mode & S_IRGRP) ? 'r' : '-';
s += (mode & S_IWGRP) ? 'w' : '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case S_IXGRP: s += 'x'; break;
case S_ISGID: s += 'S'; break;
case S_IXGRP | S_ISGID: s += 's'; break;
default: s += '-'; break;
}
// Other permissions
s += (mode & S_IROTH) ? 'r' : '-';
s += (mode & S_IWOTH) ? 'w' : '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case S_IXOTH: s += 'x'; break;
case S_ISVTX: s += 'T'; break;
case S_IXOTH | S_ISVTX: s += 't'; break;
default: s += '-'; break;
}
return s;
}
int unistd_gzopen(char* pathname, int flags, mode_t mode)
{
char* gz_mode;
switch (flags & O_ACCMODE) {
case O_WRONLY:
gz_mode = "w";
break;
case O_RDONLY:
gz_mode = "r";
break;
case O_RDWR:
default:
errno = EINVAL;
return -1;
}
int fd;
gzFile gz_file;
if ((fd = open(pathname, flags, mode)) == -1)
return -1;
if ((flags & O_CREAT) && fchmod(fd, mode))
return -1;
if (!(gz_file = gzdopen(fd, gz_mode))) {
errno = ENOMEM;
return -1;
}
return (int)gz_file;
}
string trim_filename(const string& filename)
{
string search("//");
string result = filename;
for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
result.replace(pos, search.size(), "/");
return result;
}
bool file_exists(const string& filename)
{
struct stat buf;
return !lstat(filename.c_str(), &buf);
}
bool file_empty(const string& filename)
{
struct stat buf;
if (lstat(filename.c_str(), &buf) == -1)
return false;
return (S_ISREG(buf.st_mode) && buf.st_size == 0);
}
bool file_equal(const string& file1, const string& file2)
{
struct stat buf1, buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
// Regular files
if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
ifstream f1(file1.c_str());
ifstream f2(file2.c_str());
if (!f1 || !f2)
return false;
while (!f1.eof()) {
char buffer1[4096];
char buffer2[4096];
f1.read(buffer1, 4096);
f2.read(buffer2, 4096);
if (f1.gcount() != f2.gcount() ||
memcmp(buffer1, buffer2, f1.gcount()) ||
f1.eof() != f2.eof())
return false;
}
return true;
}
// Symlinks
else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
char symlink1[MAXPATHLEN];
char symlink2[MAXPATHLEN];
memset(symlink1, 0, MAXPATHLEN);
memset(symlink2, 0, MAXPATHLEN);
if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
return false;
if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
return false;
return !strncmp(symlink1, symlink2, MAXPATHLEN);
}
// Character devices
else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
// Block devices
else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
return buf1.st_dev == buf2.st_dev;
}
return false;
}
bool permissions_equal(const string& file1, const string& file2)
{
struct stat buf1;
struct stat buf2;
if (lstat(file1.c_str(), &buf1) == -1)
return false;
if (lstat(file2.c_str(), &buf2) == -1)
return false;
return(buf1.st_mode == buf2.st_mode) &&
(buf1.st_uid == buf2.st_uid) &&
(buf1.st_gid == buf2.st_gid);
}
void file_remove(const string& basedir, const string& filename)
{
if (filename != basedir && !remove(filename.c_str())) {
char* path = strdup(filename.c_str());
file_remove(basedir, dirname(path));
free(path);
}
}
|
nipuL/pkgutils | e55714dd079a329c915776594a06a71252c20474 | write warnings and errors to stderr instead of stdout | diff --git a/ChangeLog b/ChangeLog
index 322c4e3..cdd6f1c 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,2 +1,3 @@
2006-04-14 Tilman Sauerbeck (tilman at crux nu)
* ChangeLog, NEWS: Moved old ChangeLog to NEWS
+ * pkgmk.in: Write warnings and errors to stderr instead of stdout
diff --git a/pkgmk.in b/pkgmk.in
index 62a7418..51fd8f6 100755
--- a/pkgmk.in
+++ b/pkgmk.in
@@ -1,653 +1,653 @@
#!/bin/bash
#
# pkgutils
#
# Copyright (c) 2000-2005 Per Liden
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
info() {
echo "=======> $1"
}
warning() {
- info "WARNING: $1"
+ info "WARNING: $1" >&2
}
error() {
- info "ERROR: $1"
+ info "ERROR: $1" >&2
}
get_filename() {
local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
if [ "$FILE" != "$1" ]; then
FILE="$PKGMK_SOURCE_DIR/$FILE"
fi
echo $FILE
}
check_pkgfile() {
if [ ! "$name" ]; then
error "Variable 'name' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$version" ]; then
error "Variable 'version' not specified in $PKGMK_PKGFILE."
exit 1
elif [ ! "$release" ]; then
error "Variable 'release' not specified in $PKGMK_PKGFILE."
exit 1
elif [ "`type -t build`" != "function" ]; then
error "Function 'build' not specified in $PKGMK_PKGFILE."
exit 1
fi
}
check_directory() {
if [ ! -d $1 ]; then
error "Directory '$1' does not exist."
exit 1
elif [ ! -w $1 ]; then
error "Directory '$1' not writable."
exit 1
elif [ ! -x $1 ] || [ ! -r $1 ]; then
error "Directory '$1' not readable."
exit 1
fi
}
download_file() {
info "Downloading '$1'."
if [ ! "`type -p wget`" ]; then
error "Command 'wget' not found."
exit 1
fi
LOCAL_FILENAME=`get_filename $1`
LOCAL_FILENAME_PARTIAL="$LOCAL_FILENAME.partial"
DOWNLOAD_CMD="--passive-ftp --no-directories --tries=3 --waitretry=3 \
--directory-prefix=$PKGMK_SOURCE_DIR --output-document=$LOCAL_FILENAME_PARTIAL $1"
if [ -f "$LOCAL_FILENAME_PARTIAL" ]; then
info "Partial download found, trying to resume"
RESUME_CMD="-c"
fi
while true; do
wget $RESUME_CMD $DOWNLOAD_CMD
error=$?
if [ $error != 0 ] && [ "$RESUME_CMD" ]; then
info "Partial download failed, restarting"
rm -f "$LOCAL_FILENAME_PARTIAL"
RESUME_CMD=""
else
break
fi
done
if [ $error != 0 ]; then
error "Downloading '$1' failed."
exit 1
fi
mv -f "$LOCAL_FILENAME_PARTIAL" "$LOCAL_FILENAME"
}
download_source() {
local FILE LOCAL_FILENAME
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ ! -e $LOCAL_FILENAME ]; then
if [ "$LOCAL_FILENAME" = "$FILE" ]; then
error "Source file '$LOCAL_FILENAME' not found (can not be downloaded, URL not specified)."
exit 1
else
if [ "$PKGMK_DOWNLOAD" = "yes" ]; then
download_file $FILE
else
error "Source file '$LOCAL_FILENAME' not found (use option -d to download)."
exit 1
fi
fi
fi
done
}
unpack_source() {
local FILE LOCAL_FILENAME COMMAND
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
case $LOCAL_FILENAME in
*.tar.gz|*.tar.Z|*.tgz)
COMMAND="tar -C $SRC --use-compress-program=gzip -xf $LOCAL_FILENAME" ;;
*.tar.bz2)
COMMAND="tar -C $SRC --use-compress-program=bzip2 -xf $LOCAL_FILENAME" ;;
*.zip)
COMMAND="unzip -qq -o -d $SRC $LOCAL_FILENAME" ;;
*)
COMMAND="cp $LOCAL_FILENAME $SRC" ;;
esac
echo "$COMMAND"
$COMMAND
if [ $? != 0 ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
error "Building '$TARGET' failed."
exit 1
fi
done
}
make_md5sum() {
local FILE LOCAL_FILENAMES
if [ "$source" ]; then
for FILE in ${source[@]}; do
LOCAL_FILENAMES="$LOCAL_FILENAMES `get_filename $FILE`"
done
md5sum $LOCAL_FILENAMES | sed -e 's| .*/| |' | sort -k 2
fi
}
make_footprint() {
pkginfo --footprint $TARGET | \
sed "s|\tlib/modules/`uname -r`/|\tlib/modules/<kernel-version>/|g" | \
sort -k 3
}
check_md5sum() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $PKGMK_MD5SUM ]; then
make_md5sum > $FILE.md5sum
sort -k 2 $PKGMK_MD5SUM > $FILE.md5sum.orig
diff -w -t -U 0 $FILE.md5sum.orig $FILE.md5sum | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.md5sum.diff
if [ -s $FILE.md5sum.diff ]; then
error "Md5sum mismatch found:"
- cat $FILE.md5sum.diff
+ cat $FILE.md5sum.diff >&2
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
error "Md5sum not ok."
exit 1
fi
error "Building '$TARGET' failed."
exit 1
fi
else
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum not found."
exit 1
fi
warning "Md5sum not found, creating new."
make_md5sum > $PKGMK_MD5SUM
fi
if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
info "Md5sum ok."
exit 0
fi
}
strip_files() {
local FILE FILTER
cd $PKG
if [ -f $PKGMK_ROOT/$PKGMK_NOSTRIP ]; then
FILTER="grep -v -f $PKGMK_ROOT/$PKGMK_NOSTRIP"
else
FILTER="cat"
fi
find . -type f -printf "%P\n" | $FILTER | while read FILE; do
if file -b "$FILE" | grep '^.*ELF.*executable.*not stripped$' &> /dev/null; then
strip --strip-all "$FILE"
elif file -b "$FILE" | grep '^.*ELF.*shared object.*not stripped$' &> /dev/null; then
strip --strip-unneeded "$FILE"
elif file -b "$FILE" | grep '^current ar archive$' &> /dev/null; then
strip --strip-debug "$FILE"
fi
done
}
compress_manpages() {
local FILE DIR TARGET
cd $PKG
find . -type f -path "*/man/man*/*" | while read FILE; do
if [ "$FILE" = "${FILE%%.gz}" ]; then
gzip -9 "$FILE"
fi
done
find . -type l -path "*/man/man*/*" | while read FILE; do
TARGET=`readlink -n "$FILE"`
TARGET="${TARGET##*/}"
TARGET="${TARGET%%.gz}.gz"
rm -f "$FILE"
FILE="${FILE%%.gz}.gz"
DIR=`dirname "$FILE"`
if [ -e "$DIR/$TARGET" ]; then
ln -sf "$TARGET" "$FILE"
fi
done
}
check_footprint() {
local FILE="$PKGMK_WORK_DIR/.tmp"
cd $PKGMK_ROOT
if [ -f $TARGET ]; then
make_footprint > $FILE.footprint
if [ -f $PKGMK_FOOTPRINT ]; then
sort -k 3 $PKGMK_FOOTPRINT > $FILE.footprint.orig
diff -w -t -U 0 $FILE.footprint.orig $FILE.footprint | \
sed '/^@@/d' | \
sed '/^+++/d' | \
sed '/^---/d' | \
sed 's/^+/NEW /g' | \
sed 's/^-/MISSING /g' > $FILE.footprint.diff
if [ -s $FILE.footprint.diff ]; then
error "Footprint mismatch found:"
- cat $FILE.footprint.diff
+ cat $FILE.footprint.diff >&2
BUILD_SUCCESSFUL="no"
fi
else
warning "Footprint not found, creating new."
mv $FILE.footprint $PKGMK_FOOTPRINT
fi
else
error "Package '$TARGET' was not found."
BUILD_SUCCESSFUL="no"
fi
}
build_package() {
local BUILD_SUCCESSFUL="no"
export PKG="$PKGMK_WORK_DIR/pkg"
export SRC="$PKGMK_WORK_DIR/src"
umask 022
cd $PKGMK_ROOT
rm -rf $PKGMK_WORK_DIR
mkdir -p $SRC $PKG
if [ "$PKGMK_IGNORE_MD5SUM" = "no" ]; then
check_md5sum
fi
if [ "$UID" != "0" ]; then
warning "Packages should be built as root."
fi
info "Building '$TARGET'."
unpack_source
cd $SRC
(set -e -x ; build)
if [ $? = 0 ]; then
if [ "$PKGMK_NO_STRIP" = "no" ]; then
strip_files
fi
compress_manpages
cd $PKG
info "Build result:"
tar czvvf $TARGET *
if [ $? = 0 ]; then
BUILD_SUCCESSFUL="yes"
if [ "$PKGMK_IGNORE_FOOTPRINT" = "yes" ]; then
warning "Footprint ignored."
else
check_footprint
fi
fi
fi
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
if [ "$BUILD_SUCCESSFUL" = "yes" ]; then
info "Building '$TARGET' succeeded."
else
if [ -f $TARGET ]; then
touch -r $PKGMK_ROOT/$PKGMK_PKGFILE $TARGET &> /dev/null
fi
error "Building '$TARGET' failed."
exit 1
fi
}
install_package() {
local COMMAND
info "Installing '$TARGET'."
if [ "$PKGMK_INSTALL" = "install" ]; then
COMMAND="pkgadd $TARGET"
else
COMMAND="pkgadd -u $TARGET"
fi
cd $PKGMK_ROOT
echo "$COMMAND"
$COMMAND
if [ $? = 0 ]; then
info "Installing '$TARGET' succeeded."
else
error "Installing '$TARGET' failed."
exit 1
fi
}
recursive() {
local ARGS FILE DIR
ARGS=`echo "$@" | sed -e "s/--recursive//g" -e "s/-r//g"`
for FILE in `find $PKGMK_ROOT -name $PKGMK_PKGFILE | sort`; do
DIR="`dirname $FILE`/"
if [ -d $DIR ]; then
info "Entering directory '$DIR'."
(cd $DIR && $PKGMK_COMMAND $ARGS)
info "Leaving directory '$DIR'."
fi
done
}
clean() {
local FILE LOCAL_FILENAME
if [ -f $TARGET ]; then
info "Removing $TARGET"
rm -f $TARGET
fi
for FILE in ${source[@]}; do
LOCAL_FILENAME=`get_filename $FILE`
if [ -e $LOCAL_FILENAME ] && [ "$LOCAL_FILENAME" != "$FILE" ]; then
info "Removing $LOCAL_FILENAME"
rm -f $LOCAL_FILENAME
fi
done
}
update_footprint() {
if [ ! -f $TARGET ]; then
error "Unable to update footprint. File '$TARGET' not found."
exit 1
fi
make_footprint > $PKGMK_FOOTPRINT
touch $TARGET
info "Footprint updated."
}
build_needed() {
local FILE RESULT
RESULT="yes"
if [ -f $TARGET ]; then
RESULT="no"
for FILE in $PKGMK_PKGFILE ${source[@]}; do
FILE=`get_filename $FILE`
if [ ! -e $FILE ] || [ ! $TARGET -nt $FILE ]; then
RESULT="yes"
break
fi
done
fi
echo $RESULT
}
interrupted() {
echo ""
error "Interrupted."
if [ "$PKGMK_KEEP_WORK" = "no" ]; then
rm -rf $PKGMK_WORK_DIR
fi
exit 1
}
print_help() {
echo "usage: `basename $PKGMK_COMMAND` [options]"
echo "options:"
echo " -i, --install build and install package"
echo " -u, --upgrade build and install package (as upgrade)"
echo " -r, --recursive search for and build packages recursively"
echo " -d, --download download missing source file(s)"
echo " -do, --download-only do not build, only download missing source file(s)"
echo " -utd, --up-to-date do not build, only check if package is up to date"
echo " -uf, --update-footprint update footprint using result from last build"
echo " -if, --ignore-footprint build package without checking footprint"
echo " -um, --update-md5sum update md5sum"
echo " -im, --ignore-md5sum build package without checking md5sum"
echo " -cm, --check-md5sum do not build, only check md5sum"
echo " -ns, --no-strip do not strip executable binaries or libraries"
echo " -f, --force build package even if it appears to be up to date"
echo " -c, --clean remove package and downloaded files"
echo " -kw, --keep-work keep temporary working directory"
echo " -cf, --config-file <file> use alternative configuration file"
echo " -v, --version print version and exit "
echo " -h, --help print help and exit"
}
parse_options() {
while [ "$1" ]; do
case $1 in
-i|--install)
PKGMK_INSTALL="install" ;;
-u|--upgrade)
PKGMK_INSTALL="upgrade" ;;
-r|--recursive)
PKGMK_RECURSIVE="yes" ;;
-d|--download)
PKGMK_DOWNLOAD="yes" ;;
-do|--download-only)
PKGMK_DOWNLOAD="yes"
PKGMK_DOWNLOAD_ONLY="yes" ;;
-utd|--up-to-date)
PKGMK_UP_TO_DATE="yes" ;;
-uf|--update-footprint)
PKGMK_UPDATE_FOOTPRINT="yes" ;;
-if|--ignore-footprint)
PKGMK_IGNORE_FOOTPRINT="yes" ;;
-um|--update-md5sum)
PKGMK_UPDATE_MD5SUM="yes" ;;
-im|--ignore-md5sum)
PKGMK_IGNORE_MD5SUM="yes" ;;
-cm|--check-md5sum)
PKGMK_CHECK_MD5SUM="yes" ;;
-ns|--no-strip)
PKGMK_NO_STRIP="yes" ;;
-f|--force)
PKGMK_FORCE="yes" ;;
-c|--clean)
PKGMK_CLEAN="yes" ;;
-kw|--keep-work)
PKGMK_KEEP_WORK="yes" ;;
-cf|--config-file)
if [ ! "$2" ]; then
echo "`basename $PKGMK_COMMAND`: option $1 requires an argument"
exit 1
fi
PKGMK_CONFFILE="$2"
shift ;;
-v|--version)
echo "`basename $PKGMK_COMMAND` (pkgutils) $PKGMK_VERSION"
exit 0 ;;
-h|--help)
print_help
exit 0 ;;
*)
echo "`basename $PKGMK_COMMAND`: invalid option $1"
exit 1 ;;
esac
shift
done
}
main() {
local FILE TARGET
parse_options "$@"
if [ "$PKGMK_RECURSIVE" = "yes" ]; then
recursive "$@"
exit 0
fi
for FILE in $PKGMK_PKGFILE $PKGMK_CONFFILE; do
if [ ! -f $FILE ]; then
error "File '$FILE' not found."
exit 1
fi
. $FILE
done
check_directory "$PKGMK_SOURCE_DIR"
check_directory "$PKGMK_PACKAGE_DIR"
check_directory "`dirname $PKGMK_WORK_DIR`"
check_pkgfile
TARGET="$PKGMK_PACKAGE_DIR/$name#$version-$release.pkg.tar.gz"
if [ "$PKGMK_CLEAN" = "yes" ]; then
clean
exit 0
fi
if [ "$PKGMK_UPDATE_FOOTPRINT" = "yes" ]; then
update_footprint
exit 0
fi
if [ "$PKGMK_UPDATE_MD5SUM" = "yes" ]; then
download_source
make_md5sum > $PKGMK_MD5SUM
info "Md5sum updated."
exit 0
fi
if [ "$PKGMK_DOWNLOAD_ONLY" = "yes" ]; then
download_source
exit 0
fi
if [ "$PKGMK_UP_TO_DATE" = "yes" ]; then
if [ "`build_needed`" = "yes" ]; then
info "Package '$TARGET' is not up to date."
else
info "Package '$TARGET' is up to date."
fi
exit 0
fi
if [ "`build_needed`" = "no" ] && [ "$PKGMK_FORCE" = "no" ] && [ "$PKGMK_CHECK_MD5SUM" = "no" ]; then
info "Package '$TARGET' is up to date."
else
download_source
build_package
fi
if [ "$PKGMK_INSTALL" != "no" ]; then
install_package
fi
exit 0
}
trap "interrupted" SIGHUP SIGINT SIGQUIT SIGTERM
export LC_ALL=POSIX
readonly PKGMK_VERSION="#VERSION#"
readonly PKGMK_COMMAND="$0"
readonly PKGMK_ROOT="$PWD"
PKGMK_CONFFILE="/etc/pkgmk.conf"
PKGMK_PKGFILE="Pkgfile"
PKGMK_FOOTPRINT=".footprint"
PKGMK_MD5SUM=".md5sum"
PKGMK_NOSTRIP=".nostrip"
PKGMK_SOURCE_DIR="$PWD"
PKGMK_PACKAGE_DIR="$PWD"
PKGMK_WORK_DIR="$PWD/work"
PKGMK_INSTALL="no"
PKGMK_RECURSIVE="no"
PKGMK_DOWNLOAD="no"
PKGMK_DOWNLOAD_ONLY="no"
PKGMK_UP_TO_DATE="no"
PKGMK_UPDATE_FOOTPRINT="no"
PKGMK_IGNORE_FOOTPRINT="no"
PKGMK_FORCE="no"
PKGMK_KEEP_WORK="no"
PKGMK_UPDATE_MD5SUM="no"
PKGMK_IGNORE_MD5SUM="no"
PKGMK_CHECK_MD5SUM="no"
PKGMK_NO_STRIP="no"
PKGMK_CLEAN="no"
main "$@"
# End of file
|
nipuL/pkgutils | e4b95a33c35b2fac56dd1015aa2d1eb6baf8c032 | put a note regarding the ChangeLog/NEWS move in the new ChangeLog, too | diff --git a/ChangeLog b/ChangeLog
new file mode 100644
index 0000000..322c4e3
--- /dev/null
+++ b/ChangeLog
@@ -0,0 +1,2 @@
+2006-04-14 Tilman Sauerbeck (tilman at crux nu)
+ * ChangeLog, NEWS: Moved old ChangeLog to NEWS
|
nipuL/pkgutils | 9ac667e68d3e36eb99272eac57219002ee2318e6 | Initial import | diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..96e4591
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,340 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307, 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
+
+ Appendix: How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) 19yy <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) 19yy name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/ChangeLog b/ChangeLog
new file mode 100644
index 0000000..7fffff1
--- /dev/null
+++ b/ChangeLog
@@ -0,0 +1,227 @@
+5.20 - Released 2005-05-04
+ - pkgadd/rejmerge will now consider user, group and access
+ permissions on rejected files.
+
+5.19 - Released 2005-03-29
+ - pkgadd: improved support for automatically removing
+ rejected files that are identical to already installed files.
+ - pkgmk: added support for resuming interrupted downloads.
+ Thanks to Johannes Winkelmann <[email protected]>
+ - pkgmk: added option -cm/--check-md5sum, which checks the
+ md5sum but does not build the package.
+ - libtar: fixed bug in symlink handling.
+ Thanks to Guillaume Bibaut <[email protected]>
+
+5.18 - Released 2004-05-16
+ - rejmerge: files created when merging will now get the same
+ access permissions as the installed version.
+ Thanks to Han Boetes <[email protected]>
+ - rejmerge: file diffs/merges are now piped through more(1).
+ - pkgadd/pkgrm: fixed a bug that could result in a corrupt
+ database when running low on disk space.
+ - pkgadd: directories can now be specified in rules in
+ pkgadd.conf. (This fix was supposed to be part of the 5.14
+ release, but was forgotten and actually never included).
+
+5.17 - Released 2004-05-10
+ - Fixed two bugs in rejmerge.
+
+5.16 - Released 2004-05-09
+ - pkgmk no longer redirects errors to /dev/null when removing
+ the work dir.
+ - Minor man page updates.
+
+5.15 - Released 2004-05-02
+ - Fixed bug in makefile.
+
+5.14 - Released 2004-05-02
+ - Added new utility called rejmerge.
+ See rejmerge(8) man page for more information.
+ - pkginfo -o now accepts regular expressions.
+ - Directories can now be specified in rules in pkgadd.conf.
+ - pkgadd/pkgrm now executes ldconfig after installing/removing
+ a package.
+ - Minor cleanups.
+
+5.13 - Released 2003-12-16
+ - Removed "link to ..." from .footprint.
+ - pkgmk now allows the source=() array to be empty. This
+ is useful for packages that only want create directory
+ structures and/or symlinks.
+
+5.12 - Released 2003-11-30
+ - Added support for .nostrip, an optional file containing
+ regular expressions matching files that should not be
+ stripped. Thanks to Dave Hatton <[email protected]>
+
+5.11 - Released 2003-11-27
+ - Fixed bug in footprint generation.
+ - Fixed bug in file stripping.
+
+5.10 - Released 2003-11-08
+ - pkginfo: Added option -f/--footprint, which generates a
+ package footprint. The old method for generating footprints
+ failed in special cases.
+ - pkgmk: Updated to use pkginfo -f when creating footprints.
+ - pkgmk: Fixed bug in man page compression.
+ - pkgmk: Removed support for ROOT in Pkgfiles, use PKGMK_ROOT
+ instead.
+ - pkgmk: Removed support for SOURCE_DIR, PACKAGE_DIR and
+ WORK_DIR, use PKGMK_SOURCE_DIR, PKGMK_PACKAGE_DIR and
+ PKGMK_WORK_DIR instead.
+
+5.9 - Released 2003-10-19
+ - Fixed bug in database backup code.
+ - Rejected files that are empty or equal to the already
+ installed version are now automatically removed.
+
+5.8 - Released 2003-10-03
+ - Fixed memory leak in pkgadd.
+ - Patched libtar to fix memory leak.
+ - Patched libtar to reduce memory usage.
+ - Updated default pkgadd.conf.
+
+5.7 - Released 2003-07-31
+ - pkgmk: Reintroduced the $ROOT variable.
+
+5.6 - Released 2003-07-05
+ - pkgmk: Added automatic stripping of libraries (can be
+ disabled with -ns/--no-strip).
+ - pkgmk: Added option -if/--ignore-footprint, which builds a
+ package without checking the footprint.
+ - pkgmk: Synchronized names of variables exposed in pkgmk.conf
+ to avoid potential conflicts. All variables now start with
+ PKGMK_. The old names (SOURCE_DIR, PACKAGE_DIR and WORK_DIR)
+ still work but this backwards compatibility will be removed
+ in the future.
+
+5.5 - Released 2003-05-03
+ - pkgmk: Added support for alternative source, package and work
+ directories. Variables SOURCE_DIR, PACKAGE_DIR and WORK_DIR
+ can be set in /etc/pkgmk.conf.
+ Thanks to Markus Ackermann <[email protected]>.
+ - Minor changes to some info/error messages.
+
+5.4 - Released 2003-03-09
+ - pkgmk: Added option -c/--clean, which removes the package
+ and the downloaded source files.
+ - Upgraded bundled libtar from 1.2.10 to 1.2.11. This
+ version of libtar fixes a spurious "permission denied"
+ error, which sometimes occurred when running "pkgadd -u".
+
+5.3 - Released 2003-02-05
+ - pkgadd: the combination of -f and -u now respects the
+ upgrade configuration in /etc/pkgadd.conf. This is
+ needed to better support upgrades where ownership of
+ files has been moved from one package to another.
+ - pkgadd/pkgrm/pkginfo: improved/reworked database locking
+ and error handling.
+ - pkgmk: added -o to unzip to make it behave more like tar
+ and avoid user intaraction when overwriting files.
+ Thanks to Andreas Sundström <[email protected]>.
+ - Upgraded bundled libtar from 1.2.9 to 1.2.10.
+
+5.2 - Released 2002-12-08
+ - pkgmk: exports LC_ALL=POSIX to force utilities to use a
+ neutral locate.
+ - Upgraded bundled libtar from 1.2.8 to 1.2.9.
+
+5.1 - Released 2002-10-27
+ - Upgraded bundled libtar from 1.2.5 to 1.2.8.
+ - pkgadd/pkgrm/pkginfo: Added file-locking on database to
+ prevent more than one instance of pkgadd/pkgrm/pkginfo from
+ running at the same time.
+ - pkgadd: Fixed a bug in libtar that caused segmentation fault
+ when extracting files whose filenames contains characters
+ with ascii value > 127.
+ - pkgmk: Fixed bug which caused suid/sgid binaries to become
+ unstripped.
+ - pkgmk: Added option -ns/--no-strip. Use it to avoid stripping
+ binaries in a package.
+ - pkginfo: -o/--owner does not require the whole path to the
+ file anymore.
+
+5.0 - Released 2002-09-09
+ - Now requires GCC 3.2 to compile (due to STL incompatibility).
+ - pkginfo: -o/--owner now prepends the current directory to
+ the file argument unless it starts with /. This feature is
+ disable when using the -r/--root option.
+ - pkgmk: The build() function will now be aborted as soon
+ as some command exits with an exit code other than 0 (zero).
+ - pkgmk: Binaries are now stripped automatically.
+ - pkgmk: Man pages are now compressed automatically.
+ - pkgmk: Symlinks are always given access permissions
+ lrwxrwxrwx in .footprint, regardless of the actual
+ access permissions. This avoids footprint problems
+ when using e.g. XFS.
+
+4.4 - Released 2002-06-30
+ - Added option -cf, --config-file to pkgmk.
+ - Minor bugfixes.
+
+4.3 - Released 2002-06-11
+ - Removed Pkgfile.local-feature which was added in 4.2. It
+ didn't work very well in some (common) situations.
+ - Corrected spelling errors in pkgmk.
+
+4.2 - Released 2002-05-17
+ - Added support for Pkgfile.local, which enables users to
+ tweak packages by overriding parts of the original
+ Pkgfile. This is useful when pkgmk is used in CRUX's
+ ports system, where users will loose changes made to the
+ original Pkgfile the next time they update their ports
+ structure.
+ - Minor cleanups.
+
+4.1 - Released 2002-04-08
+ - Added support for preventing selected files (typically
+ configuration files) from being overwritten when upgrading
+ a package. The file /etc/pkgadd.conf, contains a list of
+ rules with regular expressions specifying these files. These
+ rules will be consulted when executing pkgadd with the
+ option -u. Files that, according to the rules, shouldn't be
+ upgraded will instead be installed under
+ /var/lib/pkg/rejected/. The user can then examine, use and
+ remove these files manually if so desired.
+ - Added md5sum checking (.md5sum contains the MD5 checksum of
+ all source files). pkgmk uses this file to verify that
+ the (potentially downloaded) source files are correct.
+ - Upgraded bundled libtar from 1.2.4 to 1.2.5.
+
+4.0.1 - Released 2002-01-20
+ - Removed warning "unable to remove XXX: Directory not empty"
+ when upgrading a package.
+
+4.0 - Released 2002-01-14
+ - Packages are now identified by their names only (and
+ not by name and version as before). This makes it easier
+ for users to upgrade and remove packages. This, of course,
+ comes with a price. You can not install two packages with
+ the same name.
+ - The naming convention for packages is now:
+ name#version-release.pkg.tar.gz
+ The character '#' is not allowed in package names, since
+ it's used as the name/version delimiter.
+ - New database layout, which gives a more robust database
+ with a transaction-like behaviour. This implementation
+ will gurantee that the database will never be corrupted
+ even if the power fails when pkgadd/pkgrm is running. It
+ does however not guarantee that the database contents is
+ in sync with the filesystem if such a crash should occur.
+ This means that the database will _never_ loose track of
+ files that are installed, but it can (in case of a crash)
+ contain files that are actually not installed. Repeating
+ the pkgadd/pkgrm command that was running when the crash
+ occured will get the database in sync with the filesystem
+ again.
+ - pkgmk is now capable of downloading missing source files
+ (using wget) before building a package (option -d), given
+ that the URL is specified in the "source" variable.
+ - pkg.build was renamed to Pkgfile (to mimic make/Makefile).
+ - pkg.contents was renamed to .footprint.
+ - pkgmk is now capable of installing/upgrading a package if
+ the build was successful (option -i and -u).
+ - Lot's of minor fixes and cleanups.
+
+0.1 - 3.2.0 - Released 2000-05-10 - 2001-10-03
+ (No change log was maintained during this time)
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..7517a2c
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,111 @@
+#
+# pkgutils
+#
+# Copyright (c) 2000-2005 by Per Liden <[email protected]>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+# USA.
+#
+
+DESTDIR =
+BINDIR = /usr/bin
+MANDIR = /usr/man
+ETCDIR = /etc
+
+VERSION = 5.21
+LIBTAR_VERSION = 1.2.11
+
+CXXFLAGS += -DNDEBUG
+CXXFLAGS += -O2 -Wall -pedantic -D_GNU_SOURCE -DVERSION=\"$(VERSION)\" \
+ -Ilibtar-$(LIBTAR_VERSION)/lib -Ilibtar-$(LIBTAR_VERSION)/listhash
+
+LDFLAGS += -static -Llibtar-$(LIBTAR_VERSION)/lib -ltar -lz
+
+OBJECTS = main.o pkgutil.o pkgadd.o pkgrm.o pkginfo.o
+
+MANPAGES = pkgadd.8 pkgrm.8 pkginfo.8 pkgmk.8 rejmerge.8
+
+LIBTAR = libtar-$(LIBTAR_VERSION)/lib/libtar.a
+
+all: pkgadd pkgmk rejmerge man
+
+$(LIBTAR):
+ (tar xzf libtar-$(LIBTAR_VERSION).tar.gz; \
+ cd libtar-$(LIBTAR_VERSION); \
+ patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_mem_leak.patch; \
+ patch -p1 < ../libtar-$(LIBTAR_VERSION)-reduce_mem_usage.patch; \
+ patch -p1 < ../libtar-$(LIBTAR_VERSION)-fix_linkname_overflow.patch; \
+ LDFLAGS="" ./configure --disable-encap --disable-encap-install; \
+ make)
+
+pkgadd: $(LIBTAR) .depend $(OBJECTS)
+ $(CXX) $(OBJECTS) -o $@ $(LDFLAGS)
+
+pkgmk: pkgmk.in
+
+rejmerge: rejmerge.in
+
+man: $(MANPAGES)
+
+mantxt: man $(MANPAGES:=.txt)
+
+%.8.txt: %.8
+ nroff -mandoc -c $< | col -bx > $@
+
+%: %.in
+ sed -e "s/#VERSION#/$(VERSION)/" $< > $@
+
+.depend:
+ $(CXX) $(CXXFLAGS) -MM $(OBJECTS:.o=.cc) > .depend
+
+ifeq (.depend,$(wildcard .depend))
+include .depend
+endif
+
+.PHONY: install clean distclean dist
+
+dist: distclean
+ rm -rf /tmp/pkgutils-$(VERSION)
+ mkdir -p /tmp/pkgutils-$(VERSION)
+ cp -rf . /tmp/pkgutils-$(VERSION)
+ tar -C /tmp --exclude .svn -czvf ../pkgutils-$(VERSION).tar.gz pkgutils-$(VERSION)
+ rm -rf /tmp/pkgutils-$(VERSION)
+
+install: all
+ install -D -m0755 pkgadd $(DESTDIR)$(BINDIR)/pkgadd
+ install -D -m0644 pkgadd.conf $(DESTDIR)$(ETCDIR)/pkgadd.conf
+ install -D -m0755 pkgmk $(DESTDIR)$(BINDIR)/pkgmk
+ install -D -m0755 rejmerge $(DESTDIR)$(BINDIR)/rejmerge
+ install -D -m0644 pkgmk.conf $(DESTDIR)$(ETCDIR)/pkgmk.conf
+ install -D -m0644 rejmerge.conf $(DESTDIR)$(ETCDIR)/rejmerge.conf
+ install -D -m0644 pkgadd.8 $(DESTDIR)$(MANDIR)/man8/pkgadd.8
+ install -D -m0644 pkgrm.8 $(DESTDIR)$(MANDIR)/man8/pkgrm.8
+ install -D -m0644 pkginfo.8 $(DESTDIR)$(MANDIR)/man8/pkginfo.8
+ install -D -m0644 pkgmk.8 $(DESTDIR)$(MANDIR)/man8/pkgmk.8
+ install -D -m0644 rejmerge.8 $(DESTDIR)$(MANDIR)/man8/rejmerge.8
+ ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkgrm
+ ln -sf pkgadd $(DESTDIR)$(BINDIR)/pkginfo
+
+clean:
+ rm -f .depend
+ rm -f $(OBJECTS)
+ rm -f $(MANPAGES)
+ rm -f $(MANPAGES:=.txt)
+
+distclean: clean
+ rm -f pkgadd pkginfo pkgrm pkgmk rejmerge
+ rm -rf libtar-$(LIBTAR_VERSION)
+
+# End of file
diff --git a/README b/README
new file mode 100644
index 0000000..3fe0c15
--- /dev/null
+++ b/README
@@ -0,0 +1,28 @@
+
+ pkgutils - Package Management Utilities
+
+ http://www.fukt.bth.se/~per/pkgutils/
+
+
+Description
+-----------
+pkgutils is a set of utilities (pkgadd, pkgrm, pkginfo, pkgmk and rejmerge),
+which are used for managing software packages in Linux. It is developed for
+and used by the CRUX distribution (http://crux.nu).
+
+
+Building and installing
+-----------------------
+$ make
+$ make install
+or
+$ make DESTDIR=/some/other/path install
+
+
+Copyright
+---------
+pkgutils is Copyright (c) 2000-2005 Per Liden and is licensed through the
+GNU General Public License. Read the COPYING file for the complete license.
+
+pkgutils uses libtar, a library for reading/writing tar-files. This
+library is Copyright (c) 1998-2003 Mark D. Roth.
diff --git a/libtar-1.2.11-fix_linkname_overflow.patch b/libtar-1.2.11-fix_linkname_overflow.patch
new file mode 100644
index 0000000..7386dd2
--- /dev/null
+++ b/libtar-1.2.11-fix_linkname_overflow.patch
@@ -0,0 +1,35 @@
+diff -ru libtar-1.2.11/lib/decode.c libtar-1.2.11-new/lib/decode.c
+--- libtar-1.2.11/lib/decode.c 2004-08-18 22:12:06.888107160 +0200
++++ libtar-1.2.11-new/lib/decode.c 2004-08-18 22:05:27.569812768 +0200
+@@ -42,6 +42,17 @@
+ return filename;
+ }
+
++char*
++th_get_linkname(TAR* t)
++{
++ static char filename[MAXPATHLEN];
++
++ if (t->th_buf.gnu_longlink)
++ return t->th_buf.gnu_longlink;
++
++ snprintf(filename, sizeof(filename), "%.100s", t->th_buf.linkname);
++ return filename;
++}
+
+ uid_t
+ th_get_uid(TAR *t)
+diff -ru libtar-1.2.11/lib/libtar.h libtar-1.2.11-new/lib/libtar.h
+--- libtar-1.2.11/lib/libtar.h 2003-01-07 02:40:59.000000000 +0100
++++ libtar-1.2.11-new/lib/libtar.h 2004-08-18 21:59:12.344855632 +0200
+@@ -184,9 +184,7 @@
+ #define th_get_mtime(t) oct_to_int((t)->th_buf.mtime)
+ #define th_get_devmajor(t) oct_to_int((t)->th_buf.devmajor)
+ #define th_get_devminor(t) oct_to_int((t)->th_buf.devminor)
+-#define th_get_linkname(t) ((t)->th_buf.gnu_longlink \
+- ? (t)->th_buf.gnu_longlink \
+- : (t)->th_buf.linkname)
++char *th_get_linkname(TAR *t);
+ char *th_get_pathname(TAR *t);
+ mode_t th_get_mode(TAR *t);
+ uid_t th_get_uid(TAR *t);
diff --git a/libtar-1.2.11-fix_mem_leak.patch b/libtar-1.2.11-fix_mem_leak.patch
new file mode 100644
index 0000000..0b09a18
--- /dev/null
+++ b/libtar-1.2.11-fix_mem_leak.patch
@@ -0,0 +1,26 @@
+diff -ru libtar-1.2.11/lib/decode.c libtar-1.2.11-new/lib/decode.c
+--- libtar-1.2.11/lib/decode.c 2003-01-07 02:40:59.000000000 +0100
++++ libtar-1.2.11-new/lib/decode.c 2003-10-03 15:02:44.000000000 +0200
+@@ -26,7 +26,7 @@
+ char *
+ th_get_pathname(TAR *t)
+ {
+- char filename[MAXPATHLEN];
++ static char filename[MAXPATHLEN];
+
+ if (t->th_buf.gnu_longname)
+ return t->th_buf.gnu_longname;
+@@ -35,11 +35,11 @@
+ {
+ snprintf(filename, sizeof(filename), "%.155s/%.100s",
+ t->th_buf.prefix, t->th_buf.name);
+- return strdup(filename);
++ return filename;
+ }
+
+ snprintf(filename, sizeof(filename), "%.100s", t->th_buf.name);
+- return strdup(filename);
++ return filename;
+ }
+
+
diff --git a/libtar-1.2.11-reduce_mem_usage.patch b/libtar-1.2.11-reduce_mem_usage.patch
new file mode 100644
index 0000000..db28ede
--- /dev/null
+++ b/libtar-1.2.11-reduce_mem_usage.patch
@@ -0,0 +1,66 @@
+diff -ru libtar-1.2.11/lib/extract.c libtar-1.2.11-new/lib/extract.c
+--- libtar-1.2.11/lib/extract.c 2003-03-03 00:58:07.000000000 +0100
++++ libtar-1.2.11-new/lib/extract.c 2003-10-03 15:07:46.000000000 +0200
+@@ -28,14 +28,6 @@
+ #endif
+
+
+-struct linkname
+-{
+- char ln_save[MAXPATHLEN];
+- char ln_real[MAXPATHLEN];
+-};
+-typedef struct linkname linkname_t;
+-
+-
+ static int
+ tar_set_file_perms(TAR *t, char *realname)
+ {
+@@ -98,7 +90,9 @@
+ tar_extract_file(TAR *t, char *realname)
+ {
+ int i;
+- linkname_t *lnp;
++ char *lnp;
++ int pathname_len;
++ int realname_len;
+
+ if (t->options & TAR_NOOVERWRITE)
+ {
+@@ -137,11 +131,13 @@
+ if (i != 0)
+ return i;
+
+- lnp = (linkname_t *)calloc(1, sizeof(linkname_t));
++ pathname_len = strlen(th_get_pathname(t)) + 1;
++ realname_len = strlen(realname) + 1;
++ lnp = (char *)calloc(1, pathname_len + realname_len);
+ if (lnp == NULL)
+ return -1;
+- strlcpy(lnp->ln_save, th_get_pathname(t), sizeof(lnp->ln_save));
+- strlcpy(lnp->ln_real, realname, sizeof(lnp->ln_real));
++ strcpy(&lnp[0], th_get_pathname(t));
++ strcpy(&lnp[pathname_len], realname);
+ #ifdef DEBUG
+ printf("tar_extract_file(): calling libtar_hash_add(): key=\"%s\", "
+ "value=\"%s\"\n", th_get_pathname(t), realname);
+@@ -288,7 +284,7 @@
+ {
+ char *filename;
+ char *linktgt = NULL;
+- linkname_t *lnp;
++ char *lnp;
+ libtar_hashptr_t hp;
+
+ if (!TH_ISLNK(t))
+@@ -304,8 +300,8 @@
+ if (libtar_hash_getkey(t->h, &hp, th_get_linkname(t),
+ (libtar_matchfunc_t)libtar_str_match) != 0)
+ {
+- lnp = (linkname_t *)libtar_hashptr_data(&hp);
+- linktgt = lnp->ln_real;
++ lnp = (char *)libtar_hashptr_data(&hp);
++ linktgt = &lnp[strlen(lnp) + 1];
+ }
+ else
+ linktgt = th_get_linkname(t);
diff --git a/libtar-1.2.11.tar.gz b/libtar-1.2.11.tar.gz
new file mode 100644
index 0000000..ed8f796
Binary files /dev/null and b/libtar-1.2.11.tar.gz differ
diff --git a/main.cc b/main.cc
new file mode 100644
index 0000000..1681564
--- /dev/null
+++ b/main.cc
@@ -0,0 +1,76 @@
+//
+// pkgutils
+//
+// Copyright (c) 2000-2005 Per Liden
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+
+#if (__GNUC__ < 3)
+#error This program requires GCC 3.x to compile.
+#endif
+
+#include <iostream>
+#include <string>
+#include <memory>
+#include <cstdlib>
+#include <libgen.h>
+#include "pkgutil.h"
+#include "pkgadd.h"
+#include "pkgrm.h"
+#include "pkginfo.h"
+
+using namespace std;
+
+static pkgutil* select_utility(const string& name)
+{
+ if (name == "pkgadd")
+ return new pkgadd;
+ else if (name == "pkgrm")
+ return new pkgrm;
+ else if (name == "pkginfo")
+ return new pkginfo;
+ else
+ throw runtime_error("command not supported by pkgutils");
+}
+
+int main(int argc, char** argv)
+{
+ string name = basename(argv[0]);
+
+ try {
+ auto_ptr<pkgutil> util(select_utility(name));
+
+ // Handle common options
+ for (int i = 1; i < argc; i++) {
+ string option(argv[i]);
+ if (option == "-v" || option == "--version") {
+ util->print_version();
+ return EXIT_SUCCESS;
+ } else if (option == "-h" || option == "--help") {
+ util->print_help();
+ return EXIT_SUCCESS;
+ }
+ }
+
+ util->run(argc, argv);
+ } catch (runtime_error& e) {
+ cerr << name << ": " << e.what() << endl;
+ return EXIT_FAILURE;
+ }
+
+ return EXIT_SUCCESS;
+}
diff --git a/pkgadd.8.in b/pkgadd.8.in
new file mode 100644
index 0000000..1cfb195
--- /dev/null
+++ b/pkgadd.8.in
@@ -0,0 +1,68 @@
+.TH pkgadd 8 "" "pkgutils #VERSION#" ""
+.SH NAME
+pkgadd \- install software package
+.SH SYNOPSIS
+\fBpkgadd [options] <file>\fP
+.SH DESCRIPTION
+\fBpkgadd\fP is a \fIpackage management\fP utility, which installs
+a software package. A \fIpackage\fP is an archive of files (.pkg.tar.gz).
+.SH OPTIONS
+.TP
+.B "\-u, \-\-upgrade"
+Upgrade/replace package with the same name as <file>.
+.TP
+.B "\-f, \-\-force"
+Force installation, overwrite conflicting files. If the package
+that is about to be installed contains files that are already
+installed this option will cause all those files to be overwritten.
+This option should be used with care, preferably not at all.
+.TP
+.B "\-r, \-\-root <path>"
+Specify alternative installation root (default is "/"). This
+should \fInot\fP be used as a way to install software into
+e.g. /usr/local instead of /usr. Instead this should be used
+if you want to install a package on a temporary mounted partition,
+which is "owned" by another system. By using this option you not only
+specify where the software should be installed, but you also
+specify which package database to use.
+.TP
+.B "\-v, \-\-version"
+Print version and exit.
+.TP
+.B "\-h, \-\-help"
+Print help and exit.
+.SH CONFIGURATION
+When using \fBpkgadd\fP in upgrade mode (i.e. option -u is used) the
+file \fI/etc/pkgadd.conf\fP will be read. This file can contain rules describing
+how pkgadd should behave when doing upgrades. A rule is built out of three
+fragments, \fIevent\fP, \fIpattern\fP and \fIaction\fP. The event describes
+in what kind of situation this rule applies. Currently only one type of event is
+supported, that is \fBUPGRADE\fP. The pattern is a regular expression and the action
+applicable to the \fBUPGRADE\fP event is \fBYES\fP and \fBNO\fP. More than one rule of the same
+event type is allowed, in which case the first rule will have the lowest priority and the last rule
+will have the highest priority. Example:
+
+.nf
+UPGRADE ^etc/.*$ NO
+UPGRADE ^var/log/.*$ NO
+UPGRADE ^etc/X11/.*$ YES
+UPGRADE ^etc/X11/XF86Config$ NO
+.fi
+
+The above example will cause pkgadd to never upgrade anything in /etc/ or /var/log/ (subdirectories included),
+except files in /etc/X11/ (subdirectories included), unless it is the file /etc/X11/XF86Config.
+The default rule is to upgrade everything, rules in this file are exceptions to that rule.
+(NOTE! A \fIpattern\fP should never contain an initial "/" since you are referring to the files in the
+package, not the files on the disk.)
+
+If pkgadd finds that a specific file should not be upgraded it will install it under \fI/var/lib/pkg/rejected/\fP.
+The user is then free to examine/use/remove that file manually.
+.SH FILES
+.TP
+.B "/etc/pkgadd.conf"
+Configuration file.
+.SH SEE ALSO
+pkgrm(8), pkginfo(8), pkgmk(8), rejmerge(8)
+.SH COPYRIGHT
+pkgadd (pkgutils) is Copyright (c) 2000-2005 Per Liden and is licensed through
+the GNU General Public License. Read the COPYING file for the complete license.
diff --git a/pkgadd.cc b/pkgadd.cc
new file mode 100644
index 0000000..dbc5641
--- /dev/null
+++ b/pkgadd.cc
@@ -0,0 +1,206 @@
+//
+// pkgutils
+//
+// Copyright (c) 2000-2005 Per Liden
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+
+#include "pkgadd.h"
+#include <fstream>
+#include <iterator>
+#include <cstdio>
+#include <regex.h>
+#include <unistd.h>
+
+void pkgadd::run(int argc, char** argv)
+{
+ //
+ // Check command line options
+ //
+ string o_root;
+ string o_package;
+ bool o_upgrade = false;
+ bool o_force = false;
+
+ for (int i = 1; i < argc; i++) {
+ string option(argv[i]);
+ if (option == "-r" || option == "--root") {
+ assert_argument(argv, argc, i);
+ o_root = argv[i + 1];
+ i++;
+ } else if (option == "-u" || option == "--upgrade") {
+ o_upgrade = true;
+ } else if (option == "-f" || option == "--force") {
+ o_force = true;
+ } else if (option[0] == '-' || !o_package.empty()) {
+ throw runtime_error("invalid option " + option);
+ } else {
+ o_package = option;
+ }
+ }
+
+ if (o_package.empty())
+ throw runtime_error("option missing");
+
+ //
+ // Check UID
+ //
+ if (getuid())
+ throw runtime_error("only root can install/upgrade packages");
+
+ //
+ // Install/upgrade package
+ //
+ {
+ db_lock lock(o_root, true);
+ db_open(o_root);
+
+ pair<string, pkginfo_t> package = pkg_open(o_package);
+ vector<rule_t> config_rules = read_config();
+
+ bool installed = db_find_pkg(package.first);
+ if (installed && !o_upgrade)
+ throw runtime_error("package " + package.first + " already installed (use -u to upgrade)");
+ else if (!installed && o_upgrade)
+ throw runtime_error("package " + package.first + " not previously installed (skip -u to install)");
+
+ set<string> conflicting_files = db_find_conflicts(package.first, package.second);
+
+ if (!conflicting_files.empty()) {
+ if (o_force) {
+ set<string> keep_list;
+ if (o_upgrade) // Don't remove files matching the rules in configuration
+ keep_list = make_keep_list(conflicting_files, config_rules);
+ db_rm_files(conflicting_files, keep_list); // Remove unwanted conflicts
+ } else {
+ copy(conflicting_files.begin(), conflicting_files.end(), ostream_iterator<string>(cerr, "\n"));
+ throw runtime_error("listed file(s) already installed (use -f to ignore and overwrite)");
+ }
+ }
+
+ set<string> keep_list;
+
+ if (o_upgrade) {
+ keep_list = make_keep_list(package.second.files, config_rules);
+ db_rm_pkg(package.first, keep_list);
+ }
+
+ db_add_pkg(package.first, package.second);
+ db_commit();
+ pkg_install(o_package, keep_list);
+ ldconfig();
+ }
+}
+
+void pkgadd::print_help() const
+{
+ cout << "usage: " << utilname << " [options] <file>" << endl
+ << "options:" << endl
+ << " -u, --upgrade upgrade package with the same name" << endl
+ << " -f, --force force install, overwrite conflicting files" << endl
+ << " -r, --root <path> specify alternative installation root" << endl
+ << " -v, --version print version and exit" << endl
+ << " -h, --help print help and exit" << endl;
+}
+
+vector<rule_t> pkgadd::read_config() const
+{
+ vector<rule_t> rules;
+ unsigned int linecount = 0;
+ const string filename = root + PKGADD_CONF;
+ ifstream in(filename.c_str());
+
+ if (in) {
+ while (!in.eof()) {
+ string line;
+ getline(in, line);
+ linecount++;
+ if (!line.empty() && line[0] != '#') {
+ if (line.length() >= PKGADD_CONF_MAXLINE)
+ throw runtime_error(filename + ":" + itos(linecount) + ": line too long, aborting");
+
+ char event[PKGADD_CONF_MAXLINE];
+ char pattern[PKGADD_CONF_MAXLINE];
+ char action[PKGADD_CONF_MAXLINE];
+ char dummy[PKGADD_CONF_MAXLINE];
+ if (sscanf(line.c_str(), "%s %s %s %s", event, pattern, action, dummy) != 3)
+ throw runtime_error(filename + ":" + itos(linecount) + ": wrong number of arguments, aborting");
+
+ if (!strcmp(event, "UPGRADE")) {
+ rule_t rule;
+ rule.event = rule_t::UPGRADE;
+ rule.pattern = pattern;
+ if (!strcmp(action, "YES")) {
+ rule.action = true;
+ } else if (!strcmp(action, "NO")) {
+ rule.action = false;
+ } else
+ throw runtime_error(filename + ":" + itos(linecount) + ": '" +
+ string(action) + "' unknown action, should be YES or NO, aborting");
+
+ rules.push_back(rule);
+ } else
+ throw runtime_error(filename + ":" + itos(linecount) + ": '" +
+ string(event) + "' unknown event, aborting");
+ }
+ }
+ in.close();
+ }
+
+#ifndef NDEBUG
+ cerr << "Configuration:" << endl;
+ for (vector<rule_t>::const_iterator j = rules.begin(); j != rules.end(); j++) {
+ cerr << "\t" << (*j).pattern << "\t" << (*j).action << endl;
+ }
+ cerr << endl;
+#endif
+
+ return rules;
+}
+
+set<string> pkgadd::make_keep_list(const set<string>& files, const vector<rule_t>& rules) const
+{
+ set<string> keep_list;
+
+ for (set<string>::const_iterator i = files.begin(); i != files.end(); i++) {
+ for (vector<rule_t>::const_reverse_iterator j = rules.rbegin(); j != rules.rend(); j++) {
+ if ((*j).event == rule_t::UPGRADE) {
+ regex_t preg;
+ if (regcomp(&preg, (*j).pattern.c_str(), REG_EXTENDED | REG_NOSUB))
+ throw runtime_error("error compiling regular expression '" + (*j).pattern + "', aborting");
+
+ if (!regexec(&preg, (*i).c_str(), 0, 0, 0)) {
+ if (!(*j).action)
+ keep_list.insert(keep_list.end(), *i);
+ regfree(&preg);
+ break;
+ }
+ regfree(&preg);
+ }
+ }
+ }
+
+#ifndef NDEBUG
+ cerr << "Keep list:" << endl;
+ for (set<string>::const_iterator j = keep_list.begin(); j != keep_list.end(); j++) {
+ cerr << " " << (*j) << endl;
+ }
+ cerr << endl;
+#endif
+
+ return keep_list;
+}
diff --git a/pkgadd.conf b/pkgadd.conf
new file mode 100644
index 0000000..642e09b
--- /dev/null
+++ b/pkgadd.conf
@@ -0,0 +1,21 @@
+#
+# /etc/pkgadd.conf: pkgadd(8) configuration
+#
+
+# Default rule (implicit)
+#UPGRADE ^.*$ YES
+
+UPGRADE ^etc/.*$ NO
+UPGRADE ^var/log/.*$ NO
+
+UPGRADE ^etc/mail/cf/.*$ YES
+UPGRADE ^etc/ports/drivers/.*$ YES
+UPGRADE ^etc/X11/.*$ YES
+
+UPGRADE ^etc/rc.*$ YES
+UPGRADE ^etc/rc\.local$ NO
+UPGRADE ^etc/rc\.modules$ NO
+UPGRADE ^etc/rc\.conf$ NO
+UPGRADE ^etc/rc\.d/net$ NO
+
+# End of file
diff --git a/pkgadd.h b/pkgadd.h
new file mode 100644
index 0000000..46e0f1b
--- /dev/null
+++ b/pkgadd.h
@@ -0,0 +1,49 @@
+//
+// pkgutils
+//
+// Copyright (c) 2000-2005 Per Liden
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+
+#ifndef PKGADD_H
+#define PKGADD_H
+
+#include "pkgutil.h"
+#include <vector>
+#include <set>
+
+#define PKGADD_CONF "/etc/pkgadd.conf"
+#define PKGADD_CONF_MAXLINE 1024
+
+struct rule_t {
+ enum { UPGRADE } event;
+ string pattern;
+ bool action;
+};
+
+class pkgadd : public pkgutil {
+public:
+ pkgadd() : pkgutil("pkgadd") {}
+ virtual void run(int argc, char** argv);
+ virtual void print_help() const;
+
+private:
+ vector<rule_t> read_config() const;
+ set<string> make_keep_list(const set<string>& files, const vector<rule_t>& rules) const;
+};
+
+#endif /* PKGADD_H */
diff --git a/pkginfo.8.in b/pkginfo.8.in
new file mode 100644
index 0000000..e5aba54
--- /dev/null
+++ b/pkginfo.8.in
@@ -0,0 +1,41 @@
+.TH pkginfo 8 "" "pkgutils #VERSION#" ""
+.SH NAME
+pkginfo \- display software package information
+.SH SYNOPSIS
+\fBpkginfo [options]\fP
+.SH DESCRIPTION
+\fBpkginfo\fP is a \fIpackage management\fP utility, which displays
+information about software packages that are installed on the system
+or that reside in a particular directory.
+.SH OPTIONS
+.TP
+.B "\-i, \-\-installed"
+List installed packages and their version.
+.TP
+.B "\-l, \-\-list <package|file>"
+List files owned by the specified <package> or contained in <file>.
+.TP
+.B "\-o, \-\-owner <pattern>"
+List owner(s) of file(s) matching <pattern>.
+.TP
+.B "\-f, \-\-footprint <file>"
+Print footprint for <file>. This feature is mainly used by pkgmk(8)
+for creating and comparing footprints.
+.TP
+.B "\-r, \-\-root <path>"
+Specify alternative installation root (default is "/"). This
+should be used if you want to display information about a package
+that is installed on a temporary mounted partition, which is "owned"
+by another system. By using this option you specify which package
+database to use.
+.TP
+.B "\-v, \-\-version"
+Print version and exit.
+.TP
+.B "\-h, \-\-help"
+Print help and exit.
+.SH SEE ALSO
+pkgadd(8), pkgrm(8), pkgmk(8), rejmerge(8)
+.SH COPYRIGHT
+pkginfo (pkgutils) is Copyright (c) 2000-2005 Per Liden and is licensed through
+the GNU General Public License. Read the COPYING file for the complete license.
diff --git a/pkginfo.cc b/pkginfo.cc
new file mode 100644
index 0000000..76980a3
--- /dev/null
+++ b/pkginfo.cc
@@ -0,0 +1,154 @@
+//
+// pkgutils
+//
+// Copyright (c) 2000-2005 Per Liden
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+
+#include "pkginfo.h"
+#include <iterator>
+#include <vector>
+#include <iomanip>
+#include <sys/types.h>
+#include <regex.h>
+
+void pkginfo::run(int argc, char** argv)
+{
+ //
+ // Check command line options
+ //
+ int o_footprint_mode = 0;
+ int o_installed_mode = 0;
+ int o_list_mode = 0;
+ int o_owner_mode = 0;
+ string o_root;
+ string o_arg;
+
+ for (int i = 1; i < argc; ++i) {
+ string option(argv[i]);
+ if (option == "-r" || option == "--root") {
+ assert_argument(argv, argc, i);
+ o_root = argv[i + 1];
+ i++;
+ } else if (option == "-i" || option == "--installed") {
+ o_installed_mode += 1;
+ } else if (option == "-l" || option == "--list") {
+ assert_argument(argv, argc, i);
+ o_list_mode += 1;
+ o_arg = argv[i + 1];
+ i++;
+ } else if (option == "-o" || option == "--owner") {
+ assert_argument(argv, argc, i);
+ o_owner_mode += 1;
+ o_arg = argv[i + 1];
+ i++;
+ } else if (option == "-f" || option == "--footprint") {
+ assert_argument(argv, argc, i);
+ o_footprint_mode += 1;
+ o_arg = argv[i + 1];
+ i++;
+ } else {
+ throw runtime_error("invalid option " + option);
+ }
+ }
+
+ if (o_footprint_mode + o_installed_mode + o_list_mode + o_owner_mode == 0)
+ throw runtime_error("option missing");
+
+ if (o_footprint_mode + o_installed_mode + o_list_mode + o_owner_mode > 1)
+ throw runtime_error("too many options");
+
+ if (o_footprint_mode) {
+ //
+ // Make footprint
+ //
+ pkg_footprint(o_arg);
+ } else {
+ //
+ // Modes that require the database to be opened
+ //
+ {
+ db_lock lock(o_root, false);
+ db_open(o_root);
+ }
+
+ if (o_installed_mode) {
+ //
+ // List installed packages
+ //
+ for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
+ cout << i->first << ' ' << i->second.version << endl;
+ } else if (o_list_mode) {
+ //
+ // List package or file contents
+ //
+ if (db_find_pkg(o_arg)) {
+ copy(packages[o_arg].files.begin(), packages[o_arg].files.end(), ostream_iterator<string>(cout, "\n"));
+ } else if (file_exists(o_arg)) {
+ pair<string, pkginfo_t> package = pkg_open(o_arg);
+ copy(package.second.files.begin(), package.second.files.end(), ostream_iterator<string>(cout, "\n"));
+ } else {
+ throw runtime_error(o_arg + " is neither an installed package nor a package file");
+ }
+ } else {
+ //
+ // List owner(s) of file or directory
+ //
+ regex_t preg;
+ if (regcomp(&preg, o_arg.c_str(), REG_EXTENDED | REG_NOSUB))
+ throw runtime_error("error compiling regular expression '" + o_arg + "', aborting");
+
+ vector<pair<string, string> > result;
+ result.push_back(pair<string, string>("Package", "File"));
+ unsigned int width = result.begin()->first.length(); // Width of "Package"
+
+ for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
+ for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j) {
+ const string file('/' + *j);
+ if (!regexec(&preg, file.c_str(), 0, 0, 0)) {
+ result.push_back(pair<string, string>(i->first, *j));
+ if (i->first.length() > width)
+ width = i->first.length();
+ }
+ }
+ }
+
+ regfree(&preg);
+
+ if (result.size() > 1) {
+ for (vector<pair<string, string> >::const_iterator i = result.begin(); i != result.end(); ++i) {
+ cout << left << setw(width + 2) << i->first << i->second << endl;
+ }
+ } else {
+ cout << utilname << ": no owner(s) found" << endl;
+ }
+ }
+ }
+}
+
+void pkginfo::print_help() const
+{
+ cout << "usage: " << utilname << " [options]" << endl
+ << "options:" << endl
+ << " -i, --installed list installed packages" << endl
+ << " -l, --list <package|file> list files in <package> or <file>" << endl
+ << " -o, --owner <pattern> list owner(s) of file(s) matching <pattern>" << endl
+ << " -f, --footprint <file> print footprint for <file>" << endl
+ << " -r, --root <path> specify alternative installation root" << endl
+ << " -v, --version print version and exit" << endl
+ << " -h, --help print help and exit" << endl;
+}
diff --git a/pkginfo.h b/pkginfo.h
new file mode 100644
index 0000000..25a4686
--- /dev/null
+++ b/pkginfo.h
@@ -0,0 +1,34 @@
+//
+// pkgutils
+//
+// Copyright (c) 2000-2005 Per Liden
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+
+#ifndef PKGINFO_H
+#define PKGINFO_H
+
+#include "pkgutil.h"
+
+class pkginfo : public pkgutil {
+public:
+ pkginfo() : pkgutil("pkginfo") {}
+ virtual void run(int argc, char** argv);
+ virtual void print_help() const;
+};
+
+#endif /* PKGINFO_H */
diff --git a/pkgmk.8.in b/pkgmk.8.in
new file mode 100644
index 0000000..0be8d3a
--- /dev/null
+++ b/pkgmk.8.in
@@ -0,0 +1,92 @@
+.TH pkgmk 8 "" "pkgutils #VERSION#" ""
+.SH NAME
+pkgmk \- make software package
+.SH SYNOPSIS
+\fBpkgmk [options]\fP
+.SH DESCRIPTION
+\fBpkgmk\fP is a \fIpackage management\fP utility, which makes
+a software package. A \fIpackage\fP is an archive of files (.pkg.tar.gz)
+that can be installed using pkgadd(8).
+
+To prepare to use pkgmk, you must write a file named \fIPkgfile\fP
+that describes how the package should be build. Once a suitable
+\fIPkgfile\fP file exists, each time you change some source files,
+you simply execute pkgmk to bring the package up to date. The pkgmk
+program uses the \fIPkgfile\fP file and the last-modification
+times of the source files to decide if the package needs to be updated.
+
+Global build configuration is stored in \fI/etc/pkgmk.conf\fP. This
+file is read by pkgmk at startup.
+.SH OPTIONS
+.TP
+.B "\-i, \-\-install"
+Install package using pkgadd(8) after successful build.
+.TP
+.B "\-u, \-\-upgrade"
+Install package as an upgrade using pkgadd(8) after successful build.
+.TP
+.B "\-r, \-\-recursive"
+Search for and build packages recursively.
+.TP
+.B "\-d, \-\-download"
+Download missing source file(s).
+.TP
+.B "\-do, \-\-download\-only"
+Do not build, only download missing source file(s).
+.TP
+.B "\-utd, \-\-up\-to\-date"
+Do not build, only check if the package is up to date.
+.TP
+.B "\-uf, \-\-update\-footprint"
+Update footprint and treat last build as successful.
+.TP
+.B "\-if, \-\-ignore\-footprint"
+Build package without checking footprint.
+.TP
+.B "\-um, \-\-update\-md5sum"
+Update md5sum using the current source files.
+.TP
+.B "\-im, \-\-ignore\-md5sum"
+Build package without checking md5sum first.
+.TP
+.B "\-ns, \-\-no\-strip"
+Do not strip executable binaries or libraries.
+.TP
+.B "\-f, \-\-force"
+Build package even if it appears to be up to date.
+.TP
+.B "\-c, \-\-clean"
+Remove the (previously built) package and the downloaded source files.
+.TP
+.B "\-kw, \-\-keep-work"
+Keep temporary working directory.
+.TP
+.B "\-cf, \-\-config\-file <file>"
+Use alternative configuration file (default is /etc/pkgmk.conf).
+.TP
+.B "\-v, \-\-version"
+Print version and exit.
+.TP
+.B "\-h, \-\-help"
+Print help and exit.
+.SH FILES
+.TP
+.B "Pkgfile"
+Package build description.
+.TP
+.B ".footprint"
+Package footprint (used for regression testing).
+.TP
+.B ".md5sum"
+MD5 checksum of source files.
+.TP
+.B "/etc/pkgmk.conf"
+Global package make configuration.
+.TP
+.B "wget"
+Used by pkgmk to download source code.
+.SH SEE ALSO
+pkgadd(8), pkgrm(8), pkginfo(8), rejmerge(8), wget(1)
+.SH COPYRIGHT
+pkgmk (pkgutils) is Copyright (c) 2000-2005 Per Liden and is licensed through
+the GNU General Public License. Read the COPYING file for the complete license.
diff --git a/pkgmk.conf b/pkgmk.conf
new file mode 100644
index 0000000..6e70f1b
--- /dev/null
+++ b/pkgmk.conf
@@ -0,0 +1,15 @@
+#
+# /etc/pkgmk.conf: pkgmk(8) configuration
+#
+
+export CFLAGS="-O2 -march=i686 -pipe"
+export CXXFLAGS="-O2 -march=i686 -pipe"
+
+# PKGMK_SOURCE_DIR="$PWD"
+# PKGMK_PACKAGE_DIR="$PWD"
+# PKGMK_WORK_DIR="$PWD/work"
+# PKGMK_DOWNLOAD="no"
+# PKGMK_IGNORE_FOOTPRINT="no"
+# PKGMK_NO_STRIP="no"
+
+# End of file
diff --git a/pkgmk.in b/pkgmk.in
new file mode 100755
index 0000000..62a7418
--- /dev/null
+++ b/pkgmk.in
@@ -0,0 +1,653 @@
+#!/bin/bash
+#
+# pkgutils
+#
+# Copyright (c) 2000-2005 Per Liden
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+# USA.
+#
+
+info() {
+ echo "=======> $1"
+}
+
+warning() {
+ info "WARNING: $1"
+}
+
+error() {
+ info "ERROR: $1"
+}
+
+get_filename() {
+ local FILE="`echo $1 | sed 's|^.*://.*/||g'`"
+
+ if [ "$FILE" != "$1" ]; then
+ FILE="$PKGMK_SOURCE_DIR/$FILE"
+ fi
+
+ echo $FILE
+}
+
+check_pkgfile() {
+ if [ ! "$name" ]; then
+ error "Variable 'name' not specified in $PKGMK_PKGFILE."
+ exit 1
+ elif [ ! "$version" ]; then
+ error "Variable 'version' not specified in $PKGMK_PKGFILE."
+ exit 1
+ elif [ ! "$release" ]; then
+ error "Variable 'release' not specified in $PKGMK_PKGFILE."
+ exit 1
+ elif [ "`type -t build`" != "function" ]; then
+ error "Function 'build' not specified in $PKGMK_PKGFILE."
+ exit 1
+ fi
+}
+
+check_directory() {
+ if [ ! -d $1 ]; then
+ error "Directory '$1' does not exist."
+ exit 1
+ elif [ ! -w $1 ]; then
+ error "Directory '$1' not writable."
+ exit 1
+ elif [ ! -x $1 ] || [ ! -r $1 ]; then
+ error "Directory '$1' not readable."
+ exit 1
+ fi
+}
+
+download_file() {
+ info "Downloading '$1'."
+
+ if [ ! "`type -p wget`" ]; then
+ error "Command 'wget' not found."
+ exit 1
+ fi
+
+ LOCAL_FILENAME=`get_filename $1`
+ LOCAL_FILENAME_PARTIAL="$LOCAL_FILENAME.partial"
+ DOWNLOAD_CMD="--passive-ftp --no-directories --tries=3 --waitretry=3 \
+ --directory-prefix=$PKGMK_SOURCE_DIR --output-document=$LOCAL_FILENAME_PARTIAL $1"
+
+ if [ -f "$LOCAL_FILENAME_PARTIAL" ]; then
+ info "Partial download found, trying to resume"
+ RESUME_CMD="-c"
+ fi
+
+ while true; do
+ wget $RESUME_CMD $DOWNLOAD_CMD
+ error=$?
+ if [ $error != 0 ] && [ "$RESUME_CMD" ]; then
+ info "Partial download failed, restarting"
+ rm -f "$LOCAL_FILENAME_PARTIAL"
+ RESUME_CMD=""
+ else
+ break
+ fi
+ done
+
+ if [ $error != 0 ]; then
+ error "Downloading '$1' failed."
+ exit 1
+ fi
+
+ mv -f "$LOCAL_FILENAME_PARTIAL" "$LOCAL_FILENAME"
+}
+
+download_source() {
+ local FILE LOCAL_FILENAME
+
+ for FILE in ${source[@]}; do
+ LOCAL_FILENAME=`get_filename $FILE`
+ if [ ! -e $LOCAL_FILENAME ]; then
+ if [ "$LOCAL_FILENAME" = "$FILE" ]; then
+ error "Source file '$LOCAL_FILENAME' not found (can not be downloaded, URL not specified)."
+ exit 1
+ else
+ if [ "$PKGMK_DOWNLOAD" = "yes" ]; then
+ download_file $FILE
+ else
+ error "Source file '$LOCAL_FILENAME' not found (use option -d to download)."
+ exit 1
+ fi
+ fi
+ fi
+ done
+}
+
+unpack_source() {
+ local FILE LOCAL_FILENAME COMMAND
+
+ for FILE in ${source[@]}; do
+ LOCAL_FILENAME=`get_filename $FILE`
+ case $LOCAL_FILENAME in
+ *.tar.gz|*.tar.Z|*.tgz)
+ COMMAND="tar -C $SRC --use-compress-program=gzip -xf $LOCAL_FILENAME" ;;
+ *.tar.bz2)
+ COMMAND="tar -C $SRC --use-compress-program=bzip2 -xf $LOCAL_FILENAME" ;;
+ *.zip)
+ COMMAND="unzip -qq -o -d $SRC $LOCAL_FILENAME" ;;
+ *)
+ COMMAND="cp $LOCAL_FILENAME $SRC" ;;
+ esac
+
+ echo "$COMMAND"
+
+ $COMMAND
+
+ if [ $? != 0 ]; then
+ if [ "$PKGMK_KEEP_WORK" = "no" ]; then
+ rm -rf $PKGMK_WORK_DIR
+ fi
+ error "Building '$TARGET' failed."
+ exit 1
+ fi
+ done
+}
+
+make_md5sum() {
+ local FILE LOCAL_FILENAMES
+
+ if [ "$source" ]; then
+ for FILE in ${source[@]}; do
+ LOCAL_FILENAMES="$LOCAL_FILENAMES `get_filename $FILE`"
+ done
+
+ md5sum $LOCAL_FILENAMES | sed -e 's| .*/| |' | sort -k 2
+ fi
+}
+
+make_footprint() {
+ pkginfo --footprint $TARGET | \
+ sed "s|\tlib/modules/`uname -r`/|\tlib/modules/<kernel-version>/|g" | \
+ sort -k 3
+}
+
+check_md5sum() {
+ local FILE="$PKGMK_WORK_DIR/.tmp"
+
+ cd $PKGMK_ROOT
+
+ if [ -f $PKGMK_MD5SUM ]; then
+ make_md5sum > $FILE.md5sum
+ sort -k 2 $PKGMK_MD5SUM > $FILE.md5sum.orig
+ diff -w -t -U 0 $FILE.md5sum.orig $FILE.md5sum | \
+ sed '/^@@/d' | \
+ sed '/^+++/d' | \
+ sed '/^---/d' | \
+ sed 's/^+/NEW /g' | \
+ sed 's/^-/MISSING /g' > $FILE.md5sum.diff
+ if [ -s $FILE.md5sum.diff ]; then
+ error "Md5sum mismatch found:"
+ cat $FILE.md5sum.diff
+
+ if [ "$PKGMK_KEEP_WORK" = "no" ]; then
+ rm -rf $PKGMK_WORK_DIR
+ fi
+
+ if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
+ error "Md5sum not ok."
+ exit 1
+ fi
+
+ error "Building '$TARGET' failed."
+ exit 1
+ fi
+ else
+ if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
+ if [ "$PKGMK_KEEP_WORK" = "no" ]; then
+ rm -rf $PKGMK_WORK_DIR
+ fi
+ info "Md5sum not found."
+ exit 1
+ fi
+
+ warning "Md5sum not found, creating new."
+ make_md5sum > $PKGMK_MD5SUM
+ fi
+
+ if [ "$PKGMK_CHECK_MD5SUM" = "yes" ]; then
+ if [ "$PKGMK_KEEP_WORK" = "no" ]; then
+ rm -rf $PKGMK_WORK_DIR
+ fi
+ info "Md5sum ok."
+ exit 0
+ fi
+}
+
+strip_files() {
+ local FILE FILTER
+
+ cd $PKG
+
+ if [ -f $PKGMK_ROOT/$PKGMK_NOSTRIP ]; then
+ FILTER="grep -v -f $PKGMK_ROOT/$PKGMK_NOSTRIP"
+ else
+ FILTER="cat"
+ fi
+
+ find . -type f -printf "%P\n" | $FILTER | while read FILE; do
+ if file -b "$FILE" | grep '^.*ELF.*executable.*not stripped$' &> /dev/null; then
+ strip --strip-all "$FILE"
+ elif file -b "$FILE" | grep '^.*ELF.*shared object.*not stripped$' &> /dev/null; then
+ strip --strip-unneeded "$FILE"
+ elif file -b "$FILE" | grep '^current ar archive$' &> /dev/null; then
+ strip --strip-debug "$FILE"
+ fi
+ done
+}
+
+compress_manpages() {
+ local FILE DIR TARGET
+
+ cd $PKG
+
+ find . -type f -path "*/man/man*/*" | while read FILE; do
+ if [ "$FILE" = "${FILE%%.gz}" ]; then
+ gzip -9 "$FILE"
+ fi
+ done
+
+ find . -type l -path "*/man/man*/*" | while read FILE; do
+ TARGET=`readlink -n "$FILE"`
+ TARGET="${TARGET##*/}"
+ TARGET="${TARGET%%.gz}.gz"
+ rm -f "$FILE"
+ FILE="${FILE%%.gz}.gz"
+ DIR=`dirname "$FILE"`
+
+ if [ -e "$DIR/$TARGET" ]; then
+ ln -sf "$TARGET" "$FILE"
+ fi
+ done
+}
+
+check_footprint() {
+ local FILE="$PKGMK_WORK_DIR/.tmp"
+
+ cd $PKGMK_ROOT
+
+ if [ -f $TARGET ]; then
+ make_footprint > $FILE.footprint
+ if [ -f $PKGMK_FOOTPRINT ]; then
+ sort -k 3 $PKGMK_FOOTPRINT > $FILE.footprint.orig
+ diff -w -t -U 0 $FILE.footprint.orig $FILE.footprint | \
+ sed '/^@@/d' | \
+ sed '/^+++/d' | \
+ sed '/^---/d' | \
+ sed 's/^+/NEW /g' | \
+ sed 's/^-/MISSING /g' > $FILE.footprint.diff
+ if [ -s $FILE.footprint.diff ]; then
+ error "Footprint mismatch found:"
+ cat $FILE.footprint.diff
+ BUILD_SUCCESSFUL="no"
+ fi
+ else
+ warning "Footprint not found, creating new."
+ mv $FILE.footprint $PKGMK_FOOTPRINT
+ fi
+ else
+ error "Package '$TARGET' was not found."
+ BUILD_SUCCESSFUL="no"
+ fi
+}
+
+build_package() {
+ local BUILD_SUCCESSFUL="no"
+
+ export PKG="$PKGMK_WORK_DIR/pkg"
+ export SRC="$PKGMK_WORK_DIR/src"
+ umask 022
+
+ cd $PKGMK_ROOT
+ rm -rf $PKGMK_WORK_DIR
+ mkdir -p $SRC $PKG
+
+ if [ "$PKGMK_IGNORE_MD5SUM" = "no" ]; then
+ check_md5sum
+ fi
+
+ if [ "$UID" != "0" ]; then
+ warning "Packages should be built as root."
+ fi
+
+ info "Building '$TARGET'."
+
+ unpack_source
+
+ cd $SRC
+ (set -e -x ; build)
+
+ if [ $? = 0 ]; then
+ if [ "$PKGMK_NO_STRIP" = "no" ]; then
+ strip_files
+ fi
+
+ compress_manpages
+
+ cd $PKG
+ info "Build result:"
+ tar czvvf $TARGET *
+
+ if [ $? = 0 ]; then
+ BUILD_SUCCESSFUL="yes"
+
+ if [ "$PKGMK_IGNORE_FOOTPRINT" = "yes" ]; then
+ warning "Footprint ignored."
+ else
+ check_footprint
+ fi
+ fi
+ fi
+
+ if [ "$PKGMK_KEEP_WORK" = "no" ]; then
+ rm -rf $PKGMK_WORK_DIR
+ fi
+
+ if [ "$BUILD_SUCCESSFUL" = "yes" ]; then
+ info "Building '$TARGET' succeeded."
+ else
+ if [ -f $TARGET ]; then
+ touch -r $PKGMK_ROOT/$PKGMK_PKGFILE $TARGET &> /dev/null
+ fi
+ error "Building '$TARGET' failed."
+ exit 1
+ fi
+}
+
+install_package() {
+ local COMMAND
+
+ info "Installing '$TARGET'."
+
+ if [ "$PKGMK_INSTALL" = "install" ]; then
+ COMMAND="pkgadd $TARGET"
+ else
+ COMMAND="pkgadd -u $TARGET"
+ fi
+
+ cd $PKGMK_ROOT
+ echo "$COMMAND"
+ $COMMAND
+
+ if [ $? = 0 ]; then
+ info "Installing '$TARGET' succeeded."
+ else
+ error "Installing '$TARGET' failed."
+ exit 1
+ fi
+}
+
+recursive() {
+ local ARGS FILE DIR
+
+ ARGS=`echo "$@" | sed -e "s/--recursive//g" -e "s/-r//g"`
+
+ for FILE in `find $PKGMK_ROOT -name $PKGMK_PKGFILE | sort`; do
+ DIR="`dirname $FILE`/"
+ if [ -d $DIR ]; then
+ info "Entering directory '$DIR'."
+ (cd $DIR && $PKGMK_COMMAND $ARGS)
+ info "Leaving directory '$DIR'."
+ fi
+ done
+}
+
+clean() {
+ local FILE LOCAL_FILENAME
+
+ if [ -f $TARGET ]; then
+ info "Removing $TARGET"
+ rm -f $TARGET
+ fi
+
+ for FILE in ${source[@]}; do
+ LOCAL_FILENAME=`get_filename $FILE`
+ if [ -e $LOCAL_FILENAME ] && [ "$LOCAL_FILENAME" != "$FILE" ]; then
+ info "Removing $LOCAL_FILENAME"
+ rm -f $LOCAL_FILENAME
+ fi
+ done
+}
+
+update_footprint() {
+ if [ ! -f $TARGET ]; then
+ error "Unable to update footprint. File '$TARGET' not found."
+ exit 1
+ fi
+
+ make_footprint > $PKGMK_FOOTPRINT
+ touch $TARGET
+
+ info "Footprint updated."
+}
+
+build_needed() {
+ local FILE RESULT
+
+ RESULT="yes"
+ if [ -f $TARGET ]; then
+ RESULT="no"
+ for FILE in $PKGMK_PKGFILE ${source[@]}; do
+ FILE=`get_filename $FILE`
+ if [ ! -e $FILE ] || [ ! $TARGET -nt $FILE ]; then
+ RESULT="yes"
+ break
+ fi
+ done
+ fi
+
+ echo $RESULT
+}
+
+interrupted() {
+ echo ""
+ error "Interrupted."
+
+ if [ "$PKGMK_KEEP_WORK" = "no" ]; then
+ rm -rf $PKGMK_WORK_DIR
+ fi
+
+ exit 1
+}
+
+print_help() {
+ echo "usage: `basename $PKGMK_COMMAND` [options]"
+ echo "options:"
+ echo " -i, --install build and install package"
+ echo " -u, --upgrade build and install package (as upgrade)"
+ echo " -r, --recursive search for and build packages recursively"
+ echo " -d, --download download missing source file(s)"
+ echo " -do, --download-only do not build, only download missing source file(s)"
+ echo " -utd, --up-to-date do not build, only check if package is up to date"
+ echo " -uf, --update-footprint update footprint using result from last build"
+ echo " -if, --ignore-footprint build package without checking footprint"
+ echo " -um, --update-md5sum update md5sum"
+ echo " -im, --ignore-md5sum build package without checking md5sum"
+ echo " -cm, --check-md5sum do not build, only check md5sum"
+ echo " -ns, --no-strip do not strip executable binaries or libraries"
+ echo " -f, --force build package even if it appears to be up to date"
+ echo " -c, --clean remove package and downloaded files"
+ echo " -kw, --keep-work keep temporary working directory"
+ echo " -cf, --config-file <file> use alternative configuration file"
+ echo " -v, --version print version and exit "
+ echo " -h, --help print help and exit"
+}
+
+parse_options() {
+ while [ "$1" ]; do
+ case $1 in
+ -i|--install)
+ PKGMK_INSTALL="install" ;;
+ -u|--upgrade)
+ PKGMK_INSTALL="upgrade" ;;
+ -r|--recursive)
+ PKGMK_RECURSIVE="yes" ;;
+ -d|--download)
+ PKGMK_DOWNLOAD="yes" ;;
+ -do|--download-only)
+ PKGMK_DOWNLOAD="yes"
+ PKGMK_DOWNLOAD_ONLY="yes" ;;
+ -utd|--up-to-date)
+ PKGMK_UP_TO_DATE="yes" ;;
+ -uf|--update-footprint)
+ PKGMK_UPDATE_FOOTPRINT="yes" ;;
+ -if|--ignore-footprint)
+ PKGMK_IGNORE_FOOTPRINT="yes" ;;
+ -um|--update-md5sum)
+ PKGMK_UPDATE_MD5SUM="yes" ;;
+ -im|--ignore-md5sum)
+ PKGMK_IGNORE_MD5SUM="yes" ;;
+ -cm|--check-md5sum)
+ PKGMK_CHECK_MD5SUM="yes" ;;
+ -ns|--no-strip)
+ PKGMK_NO_STRIP="yes" ;;
+ -f|--force)
+ PKGMK_FORCE="yes" ;;
+ -c|--clean)
+ PKGMK_CLEAN="yes" ;;
+ -kw|--keep-work)
+ PKGMK_KEEP_WORK="yes" ;;
+ -cf|--config-file)
+ if [ ! "$2" ]; then
+ echo "`basename $PKGMK_COMMAND`: option $1 requires an argument"
+ exit 1
+ fi
+ PKGMK_CONFFILE="$2"
+ shift ;;
+ -v|--version)
+ echo "`basename $PKGMK_COMMAND` (pkgutils) $PKGMK_VERSION"
+ exit 0 ;;
+ -h|--help)
+ print_help
+ exit 0 ;;
+ *)
+ echo "`basename $PKGMK_COMMAND`: invalid option $1"
+ exit 1 ;;
+ esac
+ shift
+ done
+}
+
+main() {
+ local FILE TARGET
+
+ parse_options "$@"
+
+ if [ "$PKGMK_RECURSIVE" = "yes" ]; then
+ recursive "$@"
+ exit 0
+ fi
+
+ for FILE in $PKGMK_PKGFILE $PKGMK_CONFFILE; do
+ if [ ! -f $FILE ]; then
+ error "File '$FILE' not found."
+ exit 1
+ fi
+ . $FILE
+ done
+
+ check_directory "$PKGMK_SOURCE_DIR"
+ check_directory "$PKGMK_PACKAGE_DIR"
+ check_directory "`dirname $PKGMK_WORK_DIR`"
+
+ check_pkgfile
+
+ TARGET="$PKGMK_PACKAGE_DIR/$name#$version-$release.pkg.tar.gz"
+
+ if [ "$PKGMK_CLEAN" = "yes" ]; then
+ clean
+ exit 0
+ fi
+
+ if [ "$PKGMK_UPDATE_FOOTPRINT" = "yes" ]; then
+ update_footprint
+ exit 0
+ fi
+
+ if [ "$PKGMK_UPDATE_MD5SUM" = "yes" ]; then
+ download_source
+ make_md5sum > $PKGMK_MD5SUM
+ info "Md5sum updated."
+ exit 0
+ fi
+
+ if [ "$PKGMK_DOWNLOAD_ONLY" = "yes" ]; then
+ download_source
+ exit 0
+ fi
+
+ if [ "$PKGMK_UP_TO_DATE" = "yes" ]; then
+ if [ "`build_needed`" = "yes" ]; then
+ info "Package '$TARGET' is not up to date."
+ else
+ info "Package '$TARGET' is up to date."
+ fi
+ exit 0
+ fi
+
+ if [ "`build_needed`" = "no" ] && [ "$PKGMK_FORCE" = "no" ] && [ "$PKGMK_CHECK_MD5SUM" = "no" ]; then
+ info "Package '$TARGET' is up to date."
+ else
+ download_source
+ build_package
+ fi
+
+ if [ "$PKGMK_INSTALL" != "no" ]; then
+ install_package
+ fi
+
+ exit 0
+}
+
+trap "interrupted" SIGHUP SIGINT SIGQUIT SIGTERM
+
+export LC_ALL=POSIX
+
+readonly PKGMK_VERSION="#VERSION#"
+readonly PKGMK_COMMAND="$0"
+readonly PKGMK_ROOT="$PWD"
+
+PKGMK_CONFFILE="/etc/pkgmk.conf"
+PKGMK_PKGFILE="Pkgfile"
+PKGMK_FOOTPRINT=".footprint"
+PKGMK_MD5SUM=".md5sum"
+PKGMK_NOSTRIP=".nostrip"
+
+PKGMK_SOURCE_DIR="$PWD"
+PKGMK_PACKAGE_DIR="$PWD"
+PKGMK_WORK_DIR="$PWD/work"
+
+PKGMK_INSTALL="no"
+PKGMK_RECURSIVE="no"
+PKGMK_DOWNLOAD="no"
+PKGMK_DOWNLOAD_ONLY="no"
+PKGMK_UP_TO_DATE="no"
+PKGMK_UPDATE_FOOTPRINT="no"
+PKGMK_IGNORE_FOOTPRINT="no"
+PKGMK_FORCE="no"
+PKGMK_KEEP_WORK="no"
+PKGMK_UPDATE_MD5SUM="no"
+PKGMK_IGNORE_MD5SUM="no"
+PKGMK_CHECK_MD5SUM="no"
+PKGMK_NO_STRIP="no"
+PKGMK_CLEAN="no"
+
+main "$@"
+
+# End of file
diff --git a/pkgrm.8.in b/pkgrm.8.in
new file mode 100644
index 0000000..e7b46d2
--- /dev/null
+++ b/pkgrm.8.in
@@ -0,0 +1,27 @@
+.TH pkgrm 8 "" "pkgutils #VERSION#" ""
+.SH NAME
+pkgrm \- remove software package
+.SH SYNOPSIS
+\fBpkgrm [options] <package>\fP
+.SH DESCRIPTION
+\fBpkgrm\fP is a \fIpackage management\fP utility, which
+removes/uninstalls a previously installed software packages.
+.SH OPTIONS
+.TP
+.B "\-r, \-\-root <path>"
+Specify alternative installation root (default is "/"). This
+should be used if you want to remove a package from a temporary
+mounted partition, which is "owned" by another system. By using
+this option you not only specify where the software is installed,
+but you also specify which package database to use.
+.TP
+.B "\-v, \-\-version"
+Print version and exit.
+.TP
+.B "\-h, \-\-help"
+Print help and exit.
+.SH SEE ALSO
+pkgadd(8), pkginfo(8), pkgmk(8), rejmerge(8)
+.SH COPYRIGHT
+pkgrm (pkgutils) is Copyright (c) 2000-2005 Per Liden and is licensed through
+the GNU General Public License. Read the COPYING file for the complete license.
diff --git a/pkgrm.cc b/pkgrm.cc
new file mode 100644
index 0000000..a779f71
--- /dev/null
+++ b/pkgrm.cc
@@ -0,0 +1,78 @@
+//
+// pkgutils
+//
+// Copyright (c) 2000-2005 Per Liden
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+
+#include "pkgrm.h"
+#include <unistd.h>
+
+void pkgrm::run(int argc, char** argv)
+{
+ //
+ // Check command line options
+ //
+ string o_package;
+ string o_root;
+
+ for (int i = 1; i < argc; i++) {
+ string option(argv[i]);
+ if (option == "-r" || option == "--root") {
+ assert_argument(argv, argc, i);
+ o_root = argv[i + 1];
+ i++;
+ } else if (option[0] == '-' || !o_package.empty()) {
+ throw runtime_error("invalid option " + option);
+ } else {
+ o_package = option;
+ }
+ }
+
+ if (o_package.empty())
+ throw runtime_error("option missing");
+
+ //
+ // Check UID
+ //
+ if (getuid())
+ throw runtime_error("only root can remove packages");
+
+ //
+ // Remove package
+ //
+ {
+ db_lock lock(o_root, true);
+ db_open(o_root);
+
+ if (!db_find_pkg(o_package))
+ throw runtime_error("package " + o_package + " not installed");
+
+ db_rm_pkg(o_package);
+ ldconfig();
+ db_commit();
+ }
+}
+
+void pkgrm::print_help() const
+{
+ cout << "usage: " << utilname << " [options] <package>" << endl
+ << "options:" << endl
+ << " -r, --root <path> specify alternative installation root" << endl
+ << " -v, --version print version and exit" << endl
+ << " -h, --help print help and exit" << endl;
+}
diff --git a/pkgrm.h b/pkgrm.h
new file mode 100644
index 0000000..3958367
--- /dev/null
+++ b/pkgrm.h
@@ -0,0 +1,34 @@
+//
+// pkgutils
+//
+// Copyright (c) 2000-2005 Per Liden
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+
+#ifndef PKGRM_H
+#define PKGRM_H
+
+#include "pkgutil.h"
+
+class pkgrm : public pkgutil {
+public:
+ pkgrm() : pkgutil("pkgrm") {}
+ virtual void run(int argc, char** argv);
+ virtual void print_help() const;
+};
+
+#endif /* PKGRM_H */
diff --git a/pkgutil.cc b/pkgutil.cc
new file mode 100644
index 0000000..571dd6e
--- /dev/null
+++ b/pkgutil.cc
@@ -0,0 +1,754 @@
+//
+// pkgutils
+//
+// Copyright (c) 2000-2005 Per Liden
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+
+#include "pkgutil.h"
+#include <iostream>
+#include <fstream>
+#include <iterator>
+#include <algorithm>
+#include <cstdio>
+#include <cstring>
+#include <cerrno>
+#include <csignal>
+#include <ext/stdio_filebuf.h>
+#include <pwd.h>
+#include <grp.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <sys/file.h>
+#include <sys/param.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <zlib.h>
+#include <libgen.h>
+#include <libtar.h>
+
+using __gnu_cxx::stdio_filebuf;
+
+static tartype_t gztype = {
+ (openfunc_t)unistd_gzopen,
+ (closefunc_t)gzclose,
+ (readfunc_t)gzread,
+ (writefunc_t)gzwrite
+};
+
+pkgutil::pkgutil(const string& name)
+ : utilname(name)
+{
+ // Ignore signals
+ struct sigaction sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sa_handler = SIG_IGN;
+ sigaction(SIGHUP, &sa, 0);
+ sigaction(SIGINT, &sa, 0);
+ sigaction(SIGQUIT, &sa, 0);
+ sigaction(SIGTERM, &sa, 0);
+}
+
+void pkgutil::db_open(const string& path)
+{
+ // Read database
+ root = trim_filename(path + "/");
+ const string filename = root + PKG_DB;
+
+ int fd = open(filename.c_str(), O_RDONLY);
+ if (fd == -1)
+ throw runtime_error_with_errno("could not open " + filename);
+
+ stdio_filebuf<char> filebuf(fd, ios::in, getpagesize());
+ istream in(&filebuf);
+ if (!in)
+ throw runtime_error_with_errno("could not read " + filename);
+
+ while (!in.eof()) {
+ // Read record
+ string name;
+ pkginfo_t info;
+ getline(in, name);
+ getline(in, info.version);
+ for (;;) {
+ string file;
+ getline(in, file);
+
+ if (file.empty())
+ break; // End of record
+
+ info.files.insert(info.files.end(), file);
+ }
+ if (!info.files.empty())
+ packages[name] = info;
+ }
+
+#ifndef NDEBUG
+ cerr << packages.size() << " packages found in database" << endl;
+#endif
+}
+
+void pkgutil::db_commit()
+{
+ const string dbfilename = root + PKG_DB;
+ const string dbfilename_new = dbfilename + ".incomplete_transaction";
+ const string dbfilename_bak = dbfilename + ".backup";
+
+ // Remove failed transaction (if it exists)
+ if (unlink(dbfilename_new.c_str()) == -1 && errno != ENOENT)
+ throw runtime_error_with_errno("could not remove " + dbfilename_new);
+
+ // Write new database
+ int fd_new = creat(dbfilename_new.c_str(), 0444);
+ if (fd_new == -1)
+ throw runtime_error_with_errno("could not create " + dbfilename_new);
+
+ stdio_filebuf<char> filebuf_new(fd_new, ios::out, getpagesize());
+ ostream db_new(&filebuf_new);
+ for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
+ if (!i->second.files.empty()) {
+ db_new << i->first << "\n";
+ db_new << i->second.version << "\n";
+ copy(i->second.files.begin(), i->second.files.end(), ostream_iterator<string>(db_new, "\n"));
+ db_new << "\n";
+ }
+ }
+
+ db_new.flush();
+
+ // Make sure the new database was successfully written
+ if (!db_new)
+ throw runtime_error("could not write " + dbfilename_new);
+
+ // Synchronize file to disk
+ if (fsync(fd_new) == -1)
+ throw runtime_error_with_errno("could not synchronize " + dbfilename_new);
+
+ // Relink database backup
+ if (unlink(dbfilename_bak.c_str()) == -1 && errno != ENOENT)
+ throw runtime_error_with_errno("could not remove " + dbfilename_bak);
+ if (link(dbfilename.c_str(), dbfilename_bak.c_str()) == -1)
+ throw runtime_error_with_errno("could not create " + dbfilename_bak);
+
+ // Move new database into place
+ if (rename(dbfilename_new.c_str(), dbfilename.c_str()) == -1)
+ throw runtime_error_with_errno("could not rename " + dbfilename_new + " to " + dbfilename);
+
+#ifndef NDEBUG
+ cerr << packages.size() << " packages written to database" << endl;
+#endif
+}
+
+void pkgutil::db_add_pkg(const string& name, const pkginfo_t& info)
+{
+ packages[name] = info;
+}
+
+bool pkgutil::db_find_pkg(const string& name)
+{
+ return (packages.find(name) != packages.end());
+}
+
+void pkgutil::db_rm_pkg(const string& name)
+{
+ set<string> files = packages[name].files;
+ packages.erase(name);
+
+#ifndef NDEBUG
+ cerr << "Removing package phase 1 (all files in package):" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+
+ // Don't delete files that still have references
+ for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
+ for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
+ files.erase(*j);
+
+#ifndef NDEBUG
+ cerr << "Removing package phase 2 (files that still have references excluded):" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+
+ // Delete the files
+ for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
+ const string filename = root + *i;
+ if (file_exists(filename) && remove(filename.c_str()) == -1) {
+ const char* msg = strerror(errno);
+ cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
+ }
+ }
+}
+
+void pkgutil::db_rm_pkg(const string& name, const set<string>& keep_list)
+{
+ set<string> files = packages[name].files;
+ packages.erase(name);
+
+#ifndef NDEBUG
+ cerr << "Removing package phase 1 (all files in package):" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+
+ // Don't delete files found in the keep list
+ for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
+ files.erase(*i);
+
+#ifndef NDEBUG
+ cerr << "Removing package phase 2 (files that is in the keep list excluded):" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+
+ // Don't delete files that still have references
+ for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i)
+ for (set<string>::const_iterator j = i->second.files.begin(); j != i->second.files.end(); ++j)
+ files.erase(*j);
+
+#ifndef NDEBUG
+ cerr << "Removing package phase 3 (files that still have references excluded):" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+
+ // Delete the files
+ for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
+ const string filename = root + *i;
+ if (file_exists(filename) && remove(filename.c_str()) == -1) {
+ if (errno == ENOTEMPTY)
+ continue;
+ const char* msg = strerror(errno);
+ cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
+ }
+ }
+}
+
+void pkgutil::db_rm_files(set<string> files, const set<string>& keep_list)
+{
+ // Remove all references
+ for (packages_t::iterator i = packages.begin(); i != packages.end(); ++i)
+ for (set<string>::const_iterator j = files.begin(); j != files.end(); ++j)
+ i->second.files.erase(*j);
+
+#ifndef NDEBUG
+ cerr << "Removing files:" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+
+ // Don't delete files found in the keep list
+ for (set<string>::const_iterator i = keep_list.begin(); i != keep_list.end(); ++i)
+ files.erase(*i);
+
+ // Delete the files
+ for (set<string>::const_reverse_iterator i = files.rbegin(); i != files.rend(); ++i) {
+ const string filename = root + *i;
+ if (file_exists(filename) && remove(filename.c_str()) == -1) {
+ if (errno == ENOTEMPTY)
+ continue;
+ const char* msg = strerror(errno);
+ cerr << utilname << ": could not remove " << filename << ": " << msg << endl;
+ }
+ }
+}
+
+set<string> pkgutil::db_find_conflicts(const string& name, const pkginfo_t& info)
+{
+ set<string> files;
+
+ // Find conflicting files in database
+ for (packages_t::const_iterator i = packages.begin(); i != packages.end(); ++i) {
+ if (i->first != name) {
+ set_intersection(info.files.begin(), info.files.end(),
+ i->second.files.begin(), i->second.files.end(),
+ inserter(files, files.end()));
+ }
+ }
+
+#ifndef NDEBUG
+ cerr << "Conflicts phase 1 (conflicts in database):" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+
+ // Find conflicting files in filesystem
+ for (set<string>::iterator i = info.files.begin(); i != info.files.end(); ++i) {
+ const string filename = root + *i;
+ if (file_exists(filename) && files.find(*i) == files.end())
+ files.insert(files.end(), *i);
+ }
+
+#ifndef NDEBUG
+ cerr << "Conflicts phase 2 (conflicts in filesystem added):" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+
+ // Exclude directories
+ set<string> tmp = files;
+ for (set<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i) {
+ if ((*i)[i->length() - 1] == '/')
+ files.erase(*i);
+ }
+
+#ifndef NDEBUG
+ cerr << "Conflicts phase 3 (directories excluded):" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+
+ // If this is an upgrade, remove files already owned by this package
+ if (packages.find(name) != packages.end()) {
+ for (set<string>::const_iterator i = packages[name].files.begin(); i != packages[name].files.end(); ++i)
+ files.erase(*i);
+
+#ifndef NDEBUG
+ cerr << "Conflicts phase 4 (files already owned by this package excluded):" << endl;
+ copy(files.begin(), files.end(), ostream_iterator<string>(cerr, "\n"));
+ cerr << endl;
+#endif
+ }
+
+ return files;
+}
+
+pair<string, pkgutil::pkginfo_t> pkgutil::pkg_open(const string& filename) const
+{
+ pair<string, pkginfo_t> result;
+ unsigned int i;
+ TAR* t;
+
+ // Extract name and version from filename
+ string basename(filename, filename.rfind('/') + 1);
+ string name(basename, 0, basename.find(VERSION_DELIM));
+ string version(basename, 0, basename.rfind(PKG_EXT));
+ version.erase(0, version.find(VERSION_DELIM) == string::npos ? string::npos : version.find(VERSION_DELIM) + 1);
+
+ if (name.empty() || version.empty())
+ throw runtime_error("could not determine name and/or version of " + basename + ": Invalid package name");
+
+ result.first = name;
+ result.second.version = version;
+
+ if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
+ throw runtime_error_with_errno("could not open " + filename);
+
+ for (i = 0; !th_read(t); ++i) {
+ result.second.files.insert(result.second.files.end(), th_get_pathname(t));
+ if (TH_ISREG(t) && tar_skip_regfile(t))
+ throw runtime_error_with_errno("could not read " + filename);
+ }
+
+ if (i == 0) {
+ if (errno == 0)
+ throw runtime_error("empty package");
+ else
+ throw runtime_error("could not read " + filename);
+ }
+
+ tar_close(t);
+
+ return result;
+}
+
+void pkgutil::pkg_install(const string& filename, const set<string>& keep_list) const
+{
+ TAR* t;
+ unsigned int i;
+
+ if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
+ throw runtime_error_with_errno("could not open " + filename);
+
+ for (i = 0; !th_read(t); ++i) {
+ string archive_filename = th_get_pathname(t);
+ string reject_dir = trim_filename(root + string("/") + string(PKG_REJECTED));
+ string original_filename = trim_filename(root + string("/") + archive_filename);
+ string real_filename = original_filename;
+
+ // Check if file should be rejected
+ if (file_exists(real_filename) && keep_list.find(archive_filename) != keep_list.end())
+ real_filename = trim_filename(reject_dir + string("/") + archive_filename);
+
+ // Extract file
+ if (tar_extract_file(t, const_cast<char*>(real_filename.c_str()))) {
+ // If a file fails to install we just print an error message and
+ // continue trying to install the rest of the package.
+ const char* msg = strerror(errno);
+ cerr << utilname << ": could not install " + archive_filename << ": " << msg << endl;
+ continue;
+ }
+
+ // Check rejected file
+ if (real_filename != original_filename) {
+ bool remove_file = false;
+
+ // Directory
+ if (TH_ISDIR(t))
+ remove_file = permissions_equal(real_filename, original_filename);
+ // Other files
+ else
+ remove_file = permissions_equal(real_filename, original_filename) &&
+ (file_empty(real_filename) || file_equal(real_filename, original_filename));
+
+ // Remove rejected file or signal about its existence
+ if (remove_file)
+ file_remove(reject_dir, real_filename);
+ else
+ cout << utilname << ": rejecting " << archive_filename << ", keeping existing version" << endl;
+ }
+ }
+
+ if (i == 0) {
+ if (errno == 0)
+ throw runtime_error("empty package");
+ else
+ throw runtime_error("could not read " + filename);
+ }
+
+ tar_close(t);
+}
+
+void pkgutil::ldconfig() const
+{
+ // Only execute ldconfig if /etc/ld.so.conf exists
+ if (file_exists(root + LDCONFIG_CONF)) {
+ pid_t pid = fork();
+
+ if (pid == -1)
+ throw runtime_error_with_errno("fork() failed");
+
+ if (pid == 0) {
+ execl(LDCONFIG, LDCONFIG, "-r", root.c_str(), 0);
+ const char* msg = strerror(errno);
+ cerr << utilname << ": could not execute " << LDCONFIG << ": " << msg << endl;
+ exit(EXIT_FAILURE);
+ } else {
+ if (waitpid(pid, 0, 0) == -1)
+ throw runtime_error_with_errno("waitpid() failed");
+ }
+ }
+}
+
+void pkgutil::pkg_footprint(string& filename) const
+{
+ unsigned int i;
+ TAR* t;
+
+ if (tar_open(&t, const_cast<char*>(filename.c_str()), &gztype, O_RDONLY, 0, TAR_GNU) == -1)
+ throw runtime_error_with_errno("could not open " + filename);
+
+ for (i = 0; !th_read(t); ++i) {
+ // Access permissions
+ if (TH_ISSYM(t)) {
+ // Access permissions on symlinks differ among filesystems, e.g. XFS and ext2 have different.
+ // To avoid getting different footprints we always use "lrwxrwxrwx".
+ cout << "lrwxrwxrwx";
+ } else {
+ cout << mtos(th_get_mode(t));
+ }
+
+ cout << '\t';
+
+ // User
+ uid_t uid = th_get_uid(t);
+ struct passwd* pw = getpwuid(uid);
+ if (pw)
+ cout << pw->pw_name;
+ else
+ cout << uid;
+
+ cout << '/';
+
+ // Group
+ gid_t gid = th_get_gid(t);
+ struct group* gr = getgrgid(gid);
+ if (gr)
+ cout << gr->gr_name;
+ else
+ cout << gid;
+
+ // Filename
+ cout << '\t' << th_get_pathname(t);
+
+ // Special cases
+ if (TH_ISSYM(t)) {
+ // Symlink
+ cout << " -> " << th_get_linkname(t);
+ } else if (TH_ISCHR(t) || TH_ISBLK(t)) {
+ // Device
+ cout << " (" << th_get_devmajor(t) << ", " << th_get_devminor(t) << ")";
+ } else if (TH_ISREG(t) && !th_get_size(t)) {
+ // Empty regular file
+ cout << " (EMPTY)";
+ }
+
+ cout << '\n';
+
+ if (TH_ISREG(t) && tar_skip_regfile(t))
+ throw runtime_error_with_errno("could not read " + filename);
+ }
+
+ if (i == 0) {
+ if (errno == 0)
+ throw runtime_error("empty package");
+ else
+ throw runtime_error("could not read " + filename);
+ }
+
+ tar_close(t);
+}
+
+void pkgutil::print_version() const
+{
+ cout << utilname << " (pkgutils) " << VERSION << endl;
+}
+
+db_lock::db_lock(const string& root, bool exclusive)
+ : dir(0)
+{
+ const string dirname = trim_filename(root + string("/") + PKG_DIR);
+
+ if (!(dir = opendir(dirname.c_str())))
+ throw runtime_error_with_errno("could not read directory " + dirname);
+
+ if (flock(dirfd(dir), (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB) == -1) {
+ if (errno == EWOULDBLOCK)
+ throw runtime_error("package database is currently locked by another process");
+ else
+ throw runtime_error_with_errno("could not lock directory " + dirname);
+ }
+}
+
+db_lock::~db_lock()
+{
+ if (dir) {
+ flock(dirfd(dir), LOCK_UN);
+ closedir(dir);
+ }
+}
+
+void assert_argument(char** argv, int argc, int index)
+{
+ if (argc - 1 < index + 1)
+ throw runtime_error("option " + string(argv[index]) + " requires an argument");
+}
+
+string itos(unsigned int value)
+{
+ static char buf[20];
+ sprintf(buf, "%u", value);
+ return buf;
+}
+
+string mtos(mode_t mode)
+{
+ string s;
+
+ // File type
+ switch (mode & S_IFMT) {
+ case S_IFREG: s += '-'; break; // Regular
+ case S_IFDIR: s += 'd'; break; // Directory
+ case S_IFLNK: s += 'l'; break; // Symbolic link
+ case S_IFCHR: s += 'c'; break; // Character special
+ case S_IFBLK: s += 'b'; break; // Block special
+ case S_IFSOCK: s += 's'; break; // Socket
+ case S_IFIFO: s += 'p'; break; // Fifo
+ default: s += '?'; break; // Unknown
+ }
+
+ // User permissions
+ s += (mode & S_IRUSR) ? 'r' : '-';
+ s += (mode & S_IWUSR) ? 'w' : '-';
+ switch (mode & (S_IXUSR | S_ISUID)) {
+ case S_IXUSR: s += 'x'; break;
+ case S_ISUID: s += 'S'; break;
+ case S_IXUSR | S_ISUID: s += 's'; break;
+ default: s += '-'; break;
+ }
+
+ // Group permissions
+ s += (mode & S_IRGRP) ? 'r' : '-';
+ s += (mode & S_IWGRP) ? 'w' : '-';
+ switch (mode & (S_IXGRP | S_ISGID)) {
+ case S_IXGRP: s += 'x'; break;
+ case S_ISGID: s += 'S'; break;
+ case S_IXGRP | S_ISGID: s += 's'; break;
+ default: s += '-'; break;
+ }
+
+ // Other permissions
+ s += (mode & S_IROTH) ? 'r' : '-';
+ s += (mode & S_IWOTH) ? 'w' : '-';
+ switch (mode & (S_IXOTH | S_ISVTX)) {
+ case S_IXOTH: s += 'x'; break;
+ case S_ISVTX: s += 'T'; break;
+ case S_IXOTH | S_ISVTX: s += 't'; break;
+ default: s += '-'; break;
+ }
+
+ return s;
+}
+
+int unistd_gzopen(char* pathname, int flags, mode_t mode)
+{
+ char* gz_mode;
+
+ switch (flags & O_ACCMODE) {
+ case O_WRONLY:
+ gz_mode = "w";
+ break;
+
+ case O_RDONLY:
+ gz_mode = "r";
+ break;
+
+ case O_RDWR:
+ default:
+ errno = EINVAL;
+ return -1;
+ }
+
+ int fd;
+ gzFile gz_file;
+
+ if ((fd = open(pathname, flags, mode)) == -1)
+ return -1;
+
+ if ((flags & O_CREAT) && fchmod(fd, mode))
+ return -1;
+
+ if (!(gz_file = gzdopen(fd, gz_mode))) {
+ errno = ENOMEM;
+ return -1;
+ }
+
+ return (int)gz_file;
+}
+
+string trim_filename(const string& filename)
+{
+ string search("//");
+ string result = filename;
+
+ for (string::size_type pos = result.find(search); pos != string::npos; pos = result.find(search))
+ result.replace(pos, search.size(), "/");
+
+ return result;
+}
+
+bool file_exists(const string& filename)
+{
+ struct stat buf;
+ return !lstat(filename.c_str(), &buf);
+}
+
+bool file_empty(const string& filename)
+{
+ struct stat buf;
+
+ if (lstat(filename.c_str(), &buf) == -1)
+ return false;
+
+ return (S_ISREG(buf.st_mode) && buf.st_size == 0);
+}
+
+bool file_equal(const string& file1, const string& file2)
+{
+ struct stat buf1, buf2;
+
+ if (lstat(file1.c_str(), &buf1) == -1)
+ return false;
+
+ if (lstat(file2.c_str(), &buf2) == -1)
+ return false;
+
+ // Regular files
+ if (S_ISREG(buf1.st_mode) && S_ISREG(buf2.st_mode)) {
+ ifstream f1(file1.c_str());
+ ifstream f2(file2.c_str());
+
+ if (!f1 || !f2)
+ return false;
+
+ while (!f1.eof()) {
+ char buffer1[4096];
+ char buffer2[4096];
+ f1.read(buffer1, 4096);
+ f2.read(buffer2, 4096);
+ if (f1.gcount() != f2.gcount() ||
+ memcmp(buffer1, buffer2, f1.gcount()) ||
+ f1.eof() != f2.eof())
+ return false;
+ }
+
+ return true;
+ }
+ // Symlinks
+ else if (S_ISLNK(buf1.st_mode) && S_ISLNK(buf2.st_mode)) {
+ char symlink1[MAXPATHLEN];
+ char symlink2[MAXPATHLEN];
+
+ memset(symlink1, 0, MAXPATHLEN);
+ memset(symlink2, 0, MAXPATHLEN);
+
+ if (readlink(file1.c_str(), symlink1, MAXPATHLEN - 1) == -1)
+ return false;
+
+ if (readlink(file2.c_str(), symlink2, MAXPATHLEN - 1) == -1)
+ return false;
+
+ return !strncmp(symlink1, symlink2, MAXPATHLEN);
+ }
+ // Character devices
+ else if (S_ISCHR(buf1.st_mode) && S_ISCHR(buf2.st_mode)) {
+ return buf1.st_dev == buf2.st_dev;
+ }
+ // Block devices
+ else if (S_ISBLK(buf1.st_mode) && S_ISBLK(buf2.st_mode)) {
+ return buf1.st_dev == buf2.st_dev;
+ }
+
+ return false;
+}
+
+bool permissions_equal(const string& file1, const string& file2)
+{
+ struct stat buf1;
+ struct stat buf2;
+
+ if (lstat(file1.c_str(), &buf1) == -1)
+ return false;
+
+ if (lstat(file2.c_str(), &buf2) == -1)
+ return false;
+
+ return(buf1.st_mode == buf2.st_mode) &&
+ (buf1.st_uid == buf2.st_uid) &&
+ (buf1.st_gid == buf2.st_gid);
+}
+
+void file_remove(const string& basedir, const string& filename)
+{
+ if (filename != basedir && !remove(filename.c_str())) {
+ char* path = strdup(filename.c_str());
+ file_remove(basedir, dirname(path));
+ free(path);
+ }
+}
diff --git a/pkgutil.h b/pkgutil.h
new file mode 100644
index 0000000..9806900
--- /dev/null
+++ b/pkgutil.h
@@ -0,0 +1,108 @@
+//
+// pkgutils
+//
+// Copyright (c) 2000-2005 Per Liden
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; either version 2 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with this program; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+
+#ifndef PKGUTIL_H
+#define PKGUTIL_H
+
+#include <string>
+#include <set>
+#include <map>
+#include <iostream>
+#include <stdexcept>
+#include <cerrno>
+#include <cstring>
+#include <sys/types.h>
+#include <dirent.h>
+
+#define PKG_EXT ".pkg.tar.gz"
+#define PKG_DIR "var/lib/pkg"
+#define PKG_DB "var/lib/pkg/db"
+#define PKG_REJECTED "var/lib/pkg/rejected"
+#define VERSION_DELIM '#'
+#define LDCONFIG "/sbin/ldconfig"
+#define LDCONFIG_CONF "/etc/ld.so.conf"
+
+using namespace std;
+
+class pkgutil {
+public:
+ struct pkginfo_t {
+ string version;
+ set<string> files;
+ };
+
+ typedef map<string, pkginfo_t> packages_t;
+
+ explicit pkgutil(const string& name);
+ virtual ~pkgutil() {}
+ virtual void run(int argc, char** argv) = 0;
+ virtual void print_help() const = 0;
+ void print_version() const;
+
+protected:
+ // Database
+ void db_open(const string& path);
+ void db_commit();
+ void db_add_pkg(const string& name, const pkginfo_t& info);
+ bool db_find_pkg(const string& name);
+ void db_rm_pkg(const string& name);
+ void db_rm_pkg(const string& name, const set<string>& keep_list);
+ void db_rm_files(set<string> files, const set<string>& keep_list);
+ set<string> db_find_conflicts(const string& name, const pkginfo_t& info);
+
+ // Tar.gz
+ pair<string, pkginfo_t> pkg_open(const string& filename) const;
+ void pkg_install(const string& filename, const set<string>& keep_list) const;
+ void pkg_footprint(string& filename) const;
+ void ldconfig() const;
+
+ string utilname;
+ packages_t packages;
+ string root;
+};
+
+class db_lock {
+public:
+ db_lock(const string& root, bool exclusive);
+ ~db_lock();
+private:
+ DIR* dir;
+};
+
+class runtime_error_with_errno : public runtime_error {
+public:
+ explicit runtime_error_with_errno(const string& msg) throw()
+ : runtime_error(msg + string(": ") + strerror(errno)) {}
+};
+
+// Utility functions
+void assert_argument(char** argv, int argc, int index);
+string itos(unsigned int value);
+string mtos(mode_t mode);
+int unistd_gzopen(char* pathname, int flags, mode_t mode);
+string trim_filename(const string& filename);
+bool file_exists(const string& filename);
+bool file_empty(const string& filename);
+bool file_equal(const string& file1, const string& file2);
+bool permissions_equal(const string& file1, const string& file2);
+void file_remove(const string& basedir, const string& filename);
+
+#endif /* PKGUTIL_H */
diff --git a/rejmerge.8.in b/rejmerge.8.in
new file mode 100644
index 0000000..210d2c0
--- /dev/null
+++ b/rejmerge.8.in
@@ -0,0 +1,77 @@
+.TH rejmerge 8 "" "pkgutils #VERSION#" ""
+.SH NAME
+rejmerge \- merge files that were rejected during package upgrades
+.SH SYNOPSIS
+\fBrejmerge [options]\fP
+.SH DESCRIPTION
+\fBrejmerge\fP is a \fIpackage management\fP utility that helps you merge files that were rejected
+during package upgrades. For each rejected file found in \fI/var/lib/pkg/rejected/\fP, \fBrejmerge\fP
+will display the difference between the installed version and the rejected version. The user can then
+choose to keep the installed version, upgrade to the rejected version or perform a merge of the two.
+
+.SH OPTIONS
+.TP
+.B "\-r, \-\-root <path>"
+Specify alternative root (default is "/"). This should be used
+if you want to merge rejected files on a temporary mounted partition,
+which is "owned" by another system.
+.TP
+.B "\-v, \-\-version"
+Print version and exit.
+.TP
+.B "\-h, \-\-help"
+Print help and exit.
+.SH CONFIGURATION
+When \fBrejmerge\fP is started it will source \fI/etc/rejmerge.conf\fP.
+This file can be used to alter the way \fBrejmerge\fP displays file differences and performs file
+merges. Changing the default behaviour is done by re-defining the shell functions \fBrejmerge_diff()\fP
+and/or \fBrejmerge_merge()\fP.
+.TP
+.B rejmerge_diff()
+This function is executed once for each rejected file. Arguments \fB$1\fP and \fB$2\fP contain the paths
+to the installed and rejected files. Argument \fB$3\fP contains the path to a temporary file where this
+function should write its result. The contents of the temporary file will later be presented to the user
+as the difference between the two files.
+.TP
+.B rejmerge_merge()
+This function is executed when the user chooses to merge two files. Arguments \fB$1\fP and \fB$2\fP
+contain the paths to the installed and rejected files. Argument \fB$3\fP contains the path to a temporary
+file where this function should write its result. The contents of the temporary file will later be
+presented to the user as the merge result.
+This function also has the option to set the variable \fB$REJMERGE_MERGE_INFO\fP. The contents of this
+variable will be displayed as informational text after a merge has been performed. Its purpose is to provide
+information about the merge, e.g. "5 merge conflicts found".
+
+.PP
+Example:
+
+.nf
+#
+# /etc/rejmerge.conf: rejmerge(8) configuration
+#
+
+rejmerge_diff() {
+ # Use diff(1) to produce side-by-side output
+ diff -y $1 $2 > $3
+}
+
+rejmerge_merge() {
+ # Use sdiff(1) to merge
+ sdiff -o $3 $1 $2
+}
+
+# End of file
+.fi
+
+.SH FILES
+.TP
+.B "/etc/rejmerge.conf"
+Configuration file.
+.TP
+.B "/var/lib/pkg/rejected/"
+Directory where rejected files are stored.
+.SH SEE ALSO
+pkgadd(8), pkgrm(8), pkginfo(8), pkgmk(8)
+.SH COPYRIGHT
+rejmerge (pkgutils) is Copyright (c) 2000-2005 Per Liden and is licensed through
+the GNU General Public License. Read the COPYING file for the complete license.
diff --git a/rejmerge.conf b/rejmerge.conf
new file mode 100644
index 0000000..c80af34
--- /dev/null
+++ b/rejmerge.conf
@@ -0,0 +1,5 @@
+#
+# /etc/rejmerge.conf: rejmerge(8) configuration
+#
+
+# End of file
diff --git a/rejmerge.in b/rejmerge.in
new file mode 100755
index 0000000..e95f4df
--- /dev/null
+++ b/rejmerge.in
@@ -0,0 +1,315 @@
+#!/bin/bash
+#
+# rejmerge (pkgutils)
+#
+# Copyright (c) 2000-2005 Per Liden
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+# USA.
+#
+
+info_n() {
+ echo -n "=======> $1"
+}
+
+info() {
+ info_n "$1"
+ echo
+}
+
+interrupted() {
+ echo ""
+ info "Aborted."
+ exit 1
+}
+
+atexit() {
+ if [ -e "$TMPFILE" ]; then
+ rm -f "$TMPFILE"
+ fi
+}
+
+rejmerge_diff() {
+ diff -u "$1" "$2" > "$3"
+}
+
+rejmerge_merge() {
+ diff --old-group-format="%<" \
+ --new-group-format="%>" \
+ --changed-group-format="<<<<< MERGE CONFLICT $1 >>>>>
+%<<<<<< MERGE CONFLICT $2 >>>>>
+%><<<<< END MERGE CONFLICT >>>>>
+" \
+ "$1" "$2" > "$3"
+
+ REJMERGE_MERGE_INFO="$(grep -c '^<<<<< END MERGE CONFLICT >>>>>$' "$3") merge conflict(s)."
+}
+
+permissions_menu() {
+ while true; do
+ info "Access permissions $1"
+ stat -c '%A %U %G %n' "$1"
+ stat -c '%A %U %G %n' "$2"
+ while true; do
+ info_n "[K]eep [U]pgrade [D]iff [S]kip? "
+ read -n1 CMD
+ echo
+
+ case "$CMD" in
+ k|K) chown --reference="$1" "$2"
+ chmod --reference="$1" "$2"
+ break 2
+ ;;
+ u|U) chown --reference="$2" "$1"
+ chmod --reference="$2" "$1"
+ break 2
+ ;;
+ d|D) break 1
+ ;;
+ s|S) break 2
+ ;;
+ esac
+ done
+ done
+}
+
+merge_menu() {
+ rejmerge_merge "$1" "$2" "$TMPFILE"
+
+ while true; do
+ info "Merged $1"
+ cat "$TMPFILE" | more
+
+ if [ "$REJMERGE_MERGE_INFO" ]; then
+ info "$REJMERGE_MERGE_INFO"
+ unset REJMERGE_MERGE_INFO
+ fi
+
+ while true; do
+ info_n "[I]nstall [E]dit [V]iew [S]kip? "
+ read -n1 CMD
+ echo
+
+ case "$CMD" in
+ i|I) chmod --reference="$1" "$TMPFILE"
+ mv -f "$TMPFILE" "$1"
+ rm -f "$2"
+ break 2
+ ;;
+ e|E) $EDITOR "$TMPFILE"
+ break 1
+ ;;
+ v|V) break 1
+ ;;
+ s|S) break 2
+ ;;
+ esac
+ done
+ done
+
+ : > "$TMPFILE"
+}
+
+diff_menu() {
+ rejmerge_diff "$1" "$2" "$TMPFILE"
+
+ while true; do
+ info "$1"
+ cat "$TMPFILE" | more
+ while true; do
+ info_n "[K]eep [U]pgrade [M]erge [D]iff [S]kip? "
+ read -n1 CMD
+ echo
+
+ case "$CMD" in
+ k|K) rm -f "$2"
+ break 2
+ ;;
+ u|U) mv -f "$2" "$1"
+ break 2
+ ;;
+ m|M) merge_menu "$1" "$2"
+ break 2
+ ;;
+ d|D) break 1
+ ;;
+ s|S) break 2
+ ;;
+ esac
+ done
+ done
+
+ : > "$TMPFILE"
+}
+
+file_menu() {
+ while true; do
+ info "$1"
+ file "$1" "$2"
+ while true; do
+ info_n "[K]eep [U]pgrade [D]iff [S]kip? "
+ read -n1 CMD
+ echo
+
+ case "$CMD" in
+ k|K) rm -f "$2"
+ break 2
+ ;;
+ u|U) mv -f "$2" "$1"
+ break 2
+ ;;
+ d|D) break 1
+ ;;
+ s|S) break 2
+ ;;
+ esac
+ done
+ done
+}
+
+print_help() {
+ echo "usage: $REJMERGE_COMMAND [options]"
+ echo "options:"
+ echo " -r, --root <path> specify alternative root"
+ echo " -v, --version print version and exit "
+ echo " -h, --help print help and exit"
+}
+
+parse_options() {
+ while [ "$1" ]; do
+ case $1 in
+ -r|--root)
+ if [ ! "$2" ]; then
+ echo "$REJMERGE_COMMAND: option $1 requires an argument"
+ exit 1
+ fi
+ REJMERGE_ROOT="$2"
+ REJMERGE_CONF="$2$REJMERGE_CONF"
+ REJECTED_DIR="$2$REJECTED_DIR"
+ shift ;;
+ -v|--version)
+ echo "$REJMERGE_COMMAND (pkgutils) $REJMERGE_VERSION"
+ exit 0 ;;
+ -h|--help)
+ print_help
+ exit 0 ;;
+ *)
+ echo "$REJMERGE_COMMAND: invalid option $1"
+ exit 1 ;;
+ esac
+ shift
+ done
+
+ if [ ! -d "$REJECTED_DIR" ]; then
+ echo "$REJMERGE_COMMAND: $REJECTED_DIR not found"
+ exit 1
+ fi
+}
+
+files_regular() {
+ local STAT_FILE1=$(stat -c '%F' "$1")
+ local STAT_FILE2=$(stat -c '%F' "$2")
+
+ if [ "$STAT_FILE1" != "regular file" ]; then
+ return 1
+ fi
+
+ if [ "$STAT_FILE2" != "regular file" ]; then
+ return 1
+ fi
+
+ return 0
+}
+
+main() {
+ parse_options "$@"
+
+ if [ "$UID" != "0" ]; then
+ echo "$REJMERGE_COMMAND: only root can merge rejected files"
+ exit 1
+ fi
+
+ # Read configuration
+ if [ -f "$REJMERGE_CONF" ]; then
+ . "$REJMERGE_CONF"
+ fi
+
+ REJECTED_FILES_FOUND="no"
+
+ # Check files
+ for REJECTED_FILE in $(find $REJECTED_DIR ! -type d); do
+ INSTALLED_FILE="$REJMERGE_ROOT${REJECTED_FILE##$REJECTED_DIR}"
+
+ # Remove rejected file if there is no installed version
+ if [ ! -e "$INSTALLED_FILE" ]; then
+ rm -f "$REJECTED_FILE"
+ continue
+ fi
+
+ # Check permissions
+ local STAT_FILE1=$(stat -c '%A %U %G' "$INSTALLED_FILE")
+ local STAT_FILE2=$(stat -c '%A %U %G' "$REJECTED_FILE")
+
+ if [ "$STAT_FILE1" != "$STAT_FILE2" ]; then
+ REJECTED_FILES_FOUND="yes"
+ permissions_menu "$INSTALLED_FILE" "$REJECTED_FILE"
+ fi
+
+ # Check file types
+ if files_regular "$INSTALLED_FILE" "$REJECTED_FILE"; then
+ # Both files are regular
+ if cmp -s "$INSTALLED_FILE" "$REJECTED_FILE"; then
+ rm -f "$REJECTED_FILE"
+ else
+ REJECTED_FILES_FOUND="yes"
+ diff_menu "$INSTALLED_FILE" "$REJECTED_FILE"
+ fi
+ else
+ # At least one file is non-regular
+ REJECTED_FILES_FOUND="yes"
+ file_menu "$INSTALLED_FILE" "$REJECTED_FILE"
+ fi
+ done
+
+ # Remove empty directories
+ for DIR in $(find $REJECTED_DIR -depth -type d); do
+ if [ "$DIR" != "$REJECTED_DIR" ]; then
+ rmdir "$DIR" &> /dev/null
+ fi
+ done
+
+ if [ "$REJECTED_FILES_FOUND" = "no" ]; then
+ echo "Nothing to merge"
+ fi
+
+ exit 0
+}
+
+trap "interrupted" SIGHUP SIGINT SIGQUIT SIGTERM
+trap "atexit" EXIT
+
+export LC_ALL=POSIX
+
+readonly REJMERGE_VERSION="#VERSION#"
+readonly REJMERGE_COMMAND="${0##*/}"
+REJMERGE_ROOT=""
+REJMERGE_CONF="/etc/rejmerge.conf"
+REJECTED_DIR="/var/lib/pkg/rejected"
+EDITOR=${EDITOR:-vi}
+TMPFILE=$(mktemp) || exit 1
+
+main "$@"
+
+# End of file
|
ShepFc3/simple-ruby-backup | 6673235a40e1ea2642fe73c2cd341cf885d3f895 | Adding initial project files | diff --git a/README b/README
new file mode 100644
index 0000000..49f6f69
--- /dev/null
+++ b/README
@@ -0,0 +1,9 @@
+Steps to getting up and running:
+1. Download Ruby Backup Zip, Ruby Backup tarball, or from git.
+2. Extract the contents of the above package.
+3. Edit the backup_settings.yml.sample file and save it as backup_settings.yml
+4. run the script via âruby ruby_backup.rbâ or â./ruby_backup.rbâ
+
+Future Features:
+1. Amazon S3 Sync
+2. Database dumps
diff --git a/backup_settings.yml.sample b/backup_settings.yml.sample
new file mode 100644
index 0000000..e18ec80
--- /dev/null
+++ b/backup_settings.yml.sample
@@ -0,0 +1,11 @@
+environment:
+ rsync_path: '/usr/bin'
+backup:
+ # Relative path from rsync source folder.
+ # Seporate with ":" if using multiple excludes
+ excludes: 'Desktop:Library/Caches'
+ num_backups_to_keep: 5
+ rsync_folders:
+ # Add any number of folders you want to back up
+ # Source: Destination
+ '/Users/shep': '/Volumes/MacBackup'
diff --git a/ruby_backup.rb b/ruby_backup.rb
new file mode 100755
index 0000000..8dbaa15
--- /dev/null
+++ b/ruby_backup.rb
@@ -0,0 +1,65 @@
+#!/usr/bin/env ruby
+
+=begin
+ Author: Chris Shepherd
+ Site: http://shep-dev.com
+ Version: 0.9
+ Release Date: 2008.11.04
+ Contact: [email protected]
+=end
+
+require 'yaml'
+require 'ftools'
+require 'fileutils'
+
+def initial_run?(backup_dir)
+ Dir.entries(backup_dir).select{|dir| dir[/\b(backup)\./]}.empty?
+end
+
+def rotate_backups(num_backups_to_rotate, backup_num, backup_dir)
+ backup_num.downto 1 do |i|
+ case i
+ when num_backups_to_rotate
+ puts "Removing backup.#{i}"
+ FileUtils.rm_r("#{backup_dir}/backup.#{i}")
+ when 1
+ FileUtils.mv("#{backup_dir}/backup.current", "#{backup_dir}/backup.#{i+1}")
+ else
+ FileUtils.mv("#{backup_dir}/backup.#{i}", "#{backup_dir}/backup.#{i+1}")
+ end
+ end
+end
+
+def current_backup_num(num_backups_to_keep, backup_dir)
+ 2.upto num_backups_to_keep+1 do |i|
+ return i-1 unless File.directory?("#{backup_dir}/backup.#{i}")
+ end
+end
+
+settings = YAML::load_file('backup_settings.yml')
+exclude_directories = settings["backup"]["excludes"].split(":")
+exclude_string = exclude_directories.collect{|e| "--exclude #{e}"}.join(' ')
+
+File.open("ruby_backup.log", "w"){|log| log.write "Starting backup #{Time.now}...\n"}
+
+settings["backup"]["rsync_folders"].each{|source, dest|
+ unless initial_run?(dest)
+ backup_num = current_backup_num(settings["backup"]["num_backups_to_keep"], dest)
+ rotate_backups(settings["backup"]["num_backups_to_keep"], backup_num, dest)
+ end
+
+ if File.directory?(dest)
+ puts "About to backup #{source} to #{dest}"
+ if initial_run?(dest)
+ system("#{settings['environment']['rsync_path']}/rsync -av --delete #{exclude_string} #{source} #{dest}/backup.current >> ruby_backup.log")
+ else
+ system("#{settings['environment']['rsync_path']}/rsync -av --delete #{exclude_string} --link-dest=#{dest}/backup.2 #{source} #{dest}/backup.current >> ruby_backup.log")
+ end
+ puts "Backup completed successfully"
+ File.open("ruby_backup.log", "a"){|log| log.write "Backup complete #{Time.now}"}
+ else
+ puts "Error: Please mount or create the destination folder #{dest} and try again"
+ File.open("ruby_backup.log", "a"){|log| log.write "Backup failed #{Time.now}"}
+ exit 1
+ end
+}
|
mzp/GC | 7a2b4d1b6cecedbfddd2b2b67a49e006a98bc142 | comment追å | diff --git a/GC.v b/GC.v
index 3617acf..36f3b53 100644
--- a/GC.v
+++ b/GC.v
@@ -1,130 +1,191 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
Require Import Recdef.
-(** * operations of set *)
-Definition In {A : Type} (elem : A) (sets : set A) :=
- set_In elem sets.
+(** * éåæä½ã®å®ç¾© *)
+
+(**
+ éåã®å®è£
ãListSet以å¤ã«ãã¦ãGCæ¬ä½ãä¿®æ£ããªãã¦ããããã«ã
+ éåã«å¯¾ããæä½ãå®ç¾©ããã
+
+ ã§ããã°ãéåé¢é£ã®è£é¡ãããã§å®ç¾©ãã¦ããããã¨ãããé¢åãªã®ã§ãå¾åãã
+ *)
+Definition In {A : Type} (b : A) (B : set A) : Prop :=
+ set_In b B.
+
+Definition In_dec {A : Type} (dec : x_dec A) (b : A) (B : set A) : {In b B} + {~ In b B} :=
+ set_In_dec dec b B.
+
Definition Included {A : Type} (B C : set A) : Prop :=
forall x, In x B -> In x C.
-Definition Union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
+
+Definition union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
set_union dec B C.
-(** * Memory *)
+Definition empty {A : Type} : set A :=
+ empty_set A.
+
+Definition remove {A : Type} (dec : x_dec A) b B : set A :=
+ set_remove dec b B.
+
+Definition Disjoint {A : Type} (xs ys : set A) := forall x,
+ (In x xs -> ~ In x ys) /\ (In x ys -> ~ In x xs).
+
+Lemma union_elim: forall A (dec : x_dec A) (a : A) (B C : set A),
+ In a (union dec B C) -> In a B \/ set_In a C.
+Proof.
+unfold In, union.
+apply set_union_elim.
+Qed.
+
+(** * ã¡ã¢ãªã®ã¢ãã«å *)
+
+(**
+ ãªãã¸ã§ã¯ãã«ã¤ãããããã¼ã¯ãå®ç¾©ããã
+ æ¯è¼é¢æ° [mark_dec] ãä¸ç·ã«å®ç¾©ããã
+ *)
Inductive mark :=
| Marked : mark
| Unmarked : mark.
Definition mark_dec : forall (m1 m2 : mark), { m1 = m2} + { m1 <> m2}.
Proof.
decide equality.
Qed.
+(** ã¡ã¢ãªã¯ã¬ã³ã¼ãã¨ãã¦å®ç¾©ããã *)
Record Mem {A : Type} := mkMem {
- roots : set A; (** root objects *)
- nodes : set A; (** all objects in memory *)
- frees : set A; (** free list *)
- marker : A -> mark; (** get mark of the object *)
- pointer : A -> option A (** get next object of the object *)
+ nodes : set A; (* ã¡ã¢ãªå
ã®å
¨ãªãã¸ã§ã¯ã *)
+ roots : set A; (* ã«ã¼ããªãã¸ã§ã¯ã *)
+ frees : set A; (* ããªã¼ãªã¹ã *)
+ marker : A -> mark; (* ãªãã¸ã§ã¯ããããã¼ã¯ã¸ã®åå *)
+ next : A -> option A (* "次"ã®ãªãã¸ã§ã¯ãã¸ã®åå *)
}.
-(** * GC *)
+(** * éå
ã®å®ç¾© *)
+
+(**
+ã«ã¼ããªãã¸ã§ã¯ããã辿ãããªãã¸ã§ã¯ãã®éåããã¡ã¢ãªã®éå
(closure)ã¨ãã¦å®ç¾©ããã
-(** ** closure *)
+éå
ã¯ãã«ã¼ããªãã¸ã§ã¯ãã« [next] ãå帰çã«é©ç¨ãããã¨ã§æ±ããã
+ãã®ãããåç´ã«ã¯åæ¢æ§ã示ããªãã
+
+弿°ã«ã¡ã¢ãªå
ã®å
¨ãªãã¸ã§ã¯ããä¸ããã
+éå
ã«å ãããªãã¸ã§ã¯ããããããåé¤ãããã¨ã§ã忢æ§ã示ãã
+ *)
Lemma remove_dec : forall A (dec : x_dec A) x xs,
- set_In x xs -> length (set_remove dec x xs) < length xs.
+ In x xs -> length (remove dec x xs) < length xs.
Proof.
intros.
induction xs.
inversion H.
simpl.
destruct (dec x a).
apply Lt.lt_n_Sn.
simpl.
apply Lt.lt_n_S.
apply IHxs.
inversion H.
rewrite H0 in n.
assert False.
apply n.
reflexivity.
contradiction.
apply H0.
Qed.
+(**
+ ã«ã¼ããªãã¸ã§ã¯ãxã®éå
ãæ±ããã
+
+ éå
ã«è¿½å ãããªãã¸ã§ã¯ããxsããåé¤ãããã¨ã§ãxsã®é·ããå¿
ãæ¸å°ããããã«ããã
+*)
Function closure (A : Type) (dec : x_dec A) (next : A -> option A) (x : A) (xs : set A) {measure length xs} : set A :=
match xs with
| nil =>
- empty_set A
+ empty
| _ =>
- if set_In_dec dec x xs then
+ if In_dec dec x xs then
match next x with
- | None => x :: empty_set A
- | Some y => x :: closure A dec next y (set_remove dec x xs)
+ | None => x :: empty
+ | Some y => x :: closure A dec next y (remove dec x xs)
end
else
- empty_set A
+ empty
end.
Proof.
intros.
simpl.
destruct (dec x a).
apply Lt.lt_n_Sn.
simpl.
apply Lt.lt_n_S.
apply remove_dec.
destruct (set_In_dec dec x (a :: l)).
- inversion s.
- rewrite H in n.
- assert False.
- apply n.
- reflexivity.
- contradiction.
+ simpl in s.
+ decompose [or] s.
+ rewrite H in n.
+ assert False.
+ apply n.
+ reflexivity.
+
+ contradiction.
- tauto.
+ assumption.
- discriminate.
+ contradiction.
Qed.
+(** [closure] ãè¤æ°ã®ã«ã¼ããªãã¸ã§ã¯ãã«æ¡å¼µããã *)
Definition closures (A : Type) (dec : x_dec A) (next : A -> option A) (roots : set A) (nodes : set A) : set A :=
- fold_right (set_union dec)
+ fold_right (union dec)
(empty_set A)
(map (fun x => closure A dec next x nodes) roots).
+(** ã¡ã¢ãªã«å¯¾ãã¦ç´æ¥ãéå
ãæ±ãããããã«ããã *)
Definition closuresM {A : Type} (dec : x_dec A) (m : Mem) :=
- closures A dec (pointer m) (roots m) (nodes m).
-
-(** ** Marker utility *)
-Definition marks (A : Type) (marker : A -> mark) (ma : mark) (xs : set A) : set A :=
- filter_dec (fun x => mark_dec (marker x) ma) xs.
-
-Definition marksM {A : Type} (ma : mark) (m : Mem) :=
- marks A (marker m) ma (nodes m).
-
-(** ** main GC *)
-(** marker *)
-Definition Marker {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) : Prop :=
- roots m1 = roots m2 /\
- nodes m1 = nodes m2 /\
- frees m1 = frees m2 /\
- pointer m1 = pointer m2 /\
+ closures A dec (next m) (roots m) (nodes m).
+
+(** * GCæ¬ä½ã®å®ç¾© *)
+
+(**
+ æå®ãããã¼ã¯ãæã¤ãªãã¸ã§ã¯ãã®ã¿ãåãã ã颿°ã
+ [marks Marked m]ã§ãã¼ã¯ã®ã¤ãããªãã¸ã§ã¯ãã®ã¿ãåãåºããã
+ *)
+Definition marksM {A : Type} (ma : mark) (m : Mem (A:=A)) :=
+ filter_dec (fun x => mark_dec (marker m x) ma) (nodes m).
+
+(**
+ ãã¼ã¯ãã§ã¼ãºã®åã¨å¾ã®ã¡ã¢ãªã®é¢ä¿ãPropã¨ãã¦å®ç¾©ããã
+ å
·ä½çãªå®è£
ãå®ç¾©ãã¦ãã¾ãã¨è¨¼æãé¢åãããã§ã¯è¨ç®ã§ããããªã©ã¯æ°ã«ããªãã
+
+ [closuresM dec m2 = marksM Marked m2]ã§ãªãã®ã¯ãã«ã¼ããã辿ããªããªãã¸ã§ã¯ãã«
+ ãã¼ã¯ãã¤ãã¦ããå ´åã許容ããããã
+ é
å»¶ãã¼ã¯ã¹ã¤ã¼ãã®å ´åã ã¨ããã¼ã¯ã¥ããä½åº¦ã«ããã¦è¡ãªãããå¯è½æ§ãããã
+ ãã®å ´åãéä¸ã§ãã¥ã¼ãã¼ã¿ãã¡ã¢ãªæ§é ãå¤åãããã«ã¼ããã辿ããªããªãã¸ã§ã¯ãã«
+ ãã¼ã¯ãã¤ãã¦ããå ´åãçºçããå¯è½æ§ãããã
+ *)
+Definition MarkPhase {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
+ roots m1 = roots m2 /\
+ nodes m1 = nodes m2 /\
+ frees m1 = frees m2 /\
+ next m1 = next m2 /\
Included (closuresM dec m2) (marksM Marked m2).
-(** sweeper *)
-Definition Sweeper {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
- roots m1 = roots m2 /\
- nodes m1 = nodes m2 /\
- pointer m1 = pointer m2 /\
- frees m2 = Union dec (frees m1) (marksM Unmarked m1) /\
+(** åæ§ã«ã¹ã¤ã¼ããã§ã¼ãºåå¾ã®ã¡ã¢ãªã®é¢ä¿ãå®ç¾©ããã *)
+Definition SweepPhase {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
+ roots m1 = roots m2 /\
+ nodes m1 = nodes m2 /\
+ next m1 = next m2 /\
+ frees m2 = union dec (frees m1) (marksM Unmarked m1) /\
forall (n : A), In n (nodes m2) -> marker m2 n = Unmarked.
-(** mark & sweep GC *)
-Definition GC {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) := exists m : Mem,
- Marker dec m1 m /\ Sweeper dec m m2.
+(** GCåå¾ã®ã¡ã¢ãªã®é¢ä¿ãå®ç¾©ããã *)
+Definition GC {A : Type} (dec : x_dec A) (m1 m2 : Mem) := exists m : Mem,
+ MarkPhase dec m1 m /\ SweepPhase dec m m2.
diff --git a/GC_fact.v b/GC_fact.v
index a9b30c1..185cc5c 100644
--- a/GC_fact.v
+++ b/GC_fact.v
@@ -1,150 +1,163 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
Require Import GC.
-(** Invariant *)
+(** * Invariantã®è¨¼æ *)
+
+(**
+ æå§ãã«ç°¡åãªæ§è³ªã示ãã¦ã¿ãã
+
+ GCã®åå¾ã§ãã«ã¼ããªãã¸ã§ã¯ããããªã¼ãªã¹ãããªãã¸ã§ã¯ãå士ã®ã¤ãªã
+ ããå¤åããªããã¨ã示ãã
+*)
Definition Invariant {A : Type} (m : Mem) : Prop :=
Included (roots m) (nodes m) /\
Included (frees m) (nodes m) /\
- forall (x y :A), In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
+ forall (x y :A), In x (nodes m) -> Some y = next m x -> In y (nodes m).
-Lemma marker_invariant : forall A dec (m1 m2 : Mem (A:=A)),
- Marker dec m1 m2 -> Invariant m1 -> Invariant m2.
+(** ãã¼ã¯ãã§ã¼ãºã®åå¾ã§Invariantãä¿ããããã¨ã証æããã *)
+Lemma MarkPhase_Invariant : forall A (dec : x_dec A) (m1 m2 : Mem),
+ MarkPhase dec m1 m2 -> Invariant m1 -> Invariant m2.
Proof.
-unfold Marker, Invariant.
+unfold MarkPhase, Invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <-H1, <-H2, <-H3, <-H4.
repeat split; auto.
Qed.
-Lemma Marks_include : forall A xs marker m,
- Included (marks A marker m xs) xs.
+(** ã¹ã¤ã¼ããã§ã¼ãºã®åå¾ã§Invariantãä¿ããããã¨ã証æããã *)
+Lemma marks_Include : forall A ma (m : Mem (A:=A)),
+ Included (marksM ma m) (nodes m).
Proof.
-unfold Included, marks, In, set_In.
+unfold Included, marksM, In, set_In.
intros.
apply filter_dec_In_elim in H.
decompose [and] H.
tauto.
Qed.
-Lemma sweeper_invariant: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
- Sweeper dec m1 m2 -> Invariant m1 -> Invariant m2.
+Lemma SweepPhase_Invariant: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
+ SweepPhase dec m1 m2 -> Invariant m1 -> Invariant m2.
Proof.
-unfold Sweeper, Invariant, Union.
+unfold SweepPhase, Invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <- H1, <- H2, <- H3, H4.
repeat split; auto.
unfold Included.
intros.
-unfold In in H7.
-apply set_union_elim in H7.
+apply union_elim in H7.
decompose [or] H7.
apply H8 in H10.
tauto.
- apply (Marks_include _ _ (marker m1) Unmarked _).
+ apply (marks_Include A Unmarked _).
tauto.
Qed.
-Theorem gc_invariant : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
+(** GCã®åå¾ã§Invariantãä¿ããããã¨ã証æããã *)
+Theorem GC_Invariant : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Invariant m1 -> GC dec m1 m2 -> Invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
-apply marker_invariant in H2; auto.
-apply sweeper_invariant in H3; auto.
+apply MarkPhase_Invariant in H2; auto.
+apply SweepPhase_Invariant in H3; auto.
Qed.
-(** safety *)
-Definition Disjoint {A : Type} (xs ys : set A) := forall x,
- (set_In x xs -> ~ set_In x ys) /\ (set_In x ys -> ~ set_In x xs).
+(** Safetyã®è¨¼æ *)
+(**
+ ããªã¼ãªã¹ãã«ãããªãã¸ã§ã¯ãã¨ãã«ã¼ããã辿ãã
+ ãªãã¸ã§ã¯ãã«ã¯éè¤ããªããã¨ã証æããã
+ *)
Definition Safety {A : Type} (dec : x_dec A) (m : Mem) : Prop :=
Disjoint (frees m) (closuresM dec m).
+(**
+ Safetyãç´æ¥ç¤ºããã¨ã¯ã§ããªãã
+ ãã¼ã¯ãã§ã¼ãºã®ç´å¾ã§ã¯ãã«ã¼ããã辿ãããªãã¸ã§ã¯ãã«ã¯ãã¼ã¯ãã¤ãã¦ããªã
+ ãã¨ã示ãå¿
è¦ãããã
+*)
Definition MarksAll {A : Type} (dec : x_dec A) (m : Mem) : Prop :=
Disjoint (marksM Unmarked m) (closuresM dec m).
-Lemma sweeper_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
- Safety dec m1 -> MarksAll dec m1 -> Sweeper dec m1 m2 -> Safety dec m2.
+(** SweepPhaseã®åå¾ã§Safetyãæãç«ã¤ãã¨ã示ãã *)
+Lemma SweepPhase_Safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
+ SweepPhase dec m1 m2 -> Safety dec m1 -> MarksAll dec m1 -> Safety dec m2.
Proof.
-unfold Safety, MarksAll, Sweeper, closuresM, Disjoint, Union, In.
+unfold Safety, MarksAll, SweepPhase, closuresM, Disjoint.
intros.
-decompose [and] (H x).
+decompose [and] H.
decompose [and] (H0 x).
-decompose [and] H1.
-rewrite <- H6, <- H7, <- H8, H9.
+decompose [and] (H1 x).
+rewrite <- H2, <- H3, <- H4, H5.
split; intros.
-apply set_union_elim in H10.
- decompose [or] H10.
- apply H2 in H12.
- tauto.
-
- apply H4 in H12.
- tauto.
+apply union_elim in H11.
+ decompose [or] H11;
+ [ apply H6 in H12 | apply H9 in H12 ];
+ tauto.
intro.
- apply set_union_elim in H12.
- decompose [or] H12.
- apply H2 in H13.
- contradiction.
-
- apply H4 in H13.
+ apply union_elim in H12.
+ decompose [or] H12;
+ [ apply H6 in H13 | apply H9 in H13];
contradiction.
Qed.
Lemma marks_In : forall A m ma (x : A),
In x (marksM ma m) -> marker m x = ma.
Proof.
-unfold In, marksM, marks.
+unfold In, marksM.
intros.
apply filter_dec_In_elim in H.
decompose [and] H.
assumption.
Qed.
-Lemma marker_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
- Safety dec m1 -> Marker dec m1 m2 -> Safety dec m2 /\ MarksAll dec m2.
+(** ãã¼ã¯ãã§ã¼ãºã®åå¾ã§Safetyã¨MarksAllãæãç«ã¤ãã¨ã示ãã *)
+Lemma MarkPhase_Safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
+ MarkPhase dec m1 m2 -> Safety dec m1 -> Safety dec m2 /\ MarksAll dec m2.
Proof.
-unfold Safety, MarksAll, Marker, closuresM, Disjoint, Union, In, Included.
+unfold Safety, MarksAll, MarkPhase, closuresM, Disjoint.
intros.
-decompose [and] H0.
+decompose [and] H.
rewrite <- H1, <- H2,<- H3, <- H4.
rewrite <- H1, <- H3, <-H4 in H6.
-repeat split; intros; decompose [and] (H x); intro.
+repeat split; intros; decompose [and] (H0 x); intro.
apply H8 in H9.
contradiction.
apply H7 in H9.
contradiction.
apply (H6 x) in H9.
apply marks_In in H5.
apply marks_In in H9.
rewrite H9 in H5.
discriminate.
apply H6 in H5.
apply marks_In in H5.
apply marks_In in H9.
rewrite H9 in H5.
discriminate.
Qed.
-Theorem gc_safety: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
- Safety dec m1 -> GC dec m1 m2 -> Safety dec m2.
+(** GCã®åå¾ã§Safetyãæãç«ã¤ãã¨ã示ãã *)
+Theorem GC_Safety: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
+ GC dec m1 m2 -> Safety dec m1 -> Safety dec m2.
Proof.
unfold GC.
intros.
-decompose [ex and] H0; auto.
-apply marker_safety in H2; auto.
+decompose [ex and] H; auto.
+apply MarkPhase_Safety in H2; auto.
decompose [and] H2.
-apply sweeper_safety in H3; auto.
+apply SweepPhase_Safety in H3; auto.
Qed.
diff --git a/GC_impl.v b/GC_impl.v
index 7b7c448..4bee3b0 100644
--- a/GC_impl.v
+++ b/GC_impl.v
@@ -1,137 +1,143 @@
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import GC.
Require Import Util.
-Require Import ExtractUtil.
-Definition markerPhase {A : Type} (dec : x_dec A) (m : Mem) :=
+(** * GCã®å®ç¾© *)
+
+(** å®éã«å®è¡ã§ããå½¢ã§mark_phaseã¨sweepr_phaseãå®è£
ããã *)
+Definition mark_phase {A : Type} (dec : x_dec A) (m : Mem) :=
let marks :=
closuresM dec m
in
- mkMem A (roots m)
- (nodes m)
+ mkMem A (nodes m)
+ (roots m)
(frees m)
- (fun x => if set_In_dec dec x marks then Marked else Unmarked)
- (pointer m).
+ (fun x => if In_dec dec x marks then Marked else Unmarked)
+ (next m).
-Definition sweeper {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
- mkMem A (roots m)
- (nodes m)
- (set_union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Unmarked) @@ nodes m))
+Definition sweep_phase {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
+ mkMem A (nodes m)
+ (roots m)
+ (union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Unmarked) @@ nodes m))
(fun _ => Unmarked)
- (pointer m).
+ (next m).
Definition gc {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
- sweeper dec (markerPhase dec m).
+ sweep_phase dec (mark_phase dec m).
+(** * æ£å½æ§ã®è¨¼æ
+å®è£
ã®æ£å½æ§ã示ãããã«ãmakr_phaseã®çµæãMarkPhaseãæºããã¨ã示ãã
+*)
Lemma remove_In : forall A (dec : x_dec A) x y xs,
- set_In y (set_remove dec x xs) -> set_In y xs.
+ In y (remove dec x xs) -> In y xs.
Proof.
induction xs; simpl; intros.
contradiction.
destruct (dec x a).
right.
assumption.
inversion H.
left.
assumption.
apply IHxs in H0.
right.
assumption.
Qed.
Lemma closure_In: forall A (dec : x_dec A) next x y xs,
- set_In y (closure A dec next x xs) -> set_In y xs.
+ In y (closure A dec next x xs) -> In y xs.
Proof.
intros until xs.
pattern x, xs, (closure A dec next x xs).
apply closure_ind; simpl; intros.
contradiction.
rewrite <- e.
decompose [or] H.
rewrite <- H0.
assumption.
contradiction.
rewrite <- e.
decompose [or] H0.
rewrite <- H1.
assumption.
apply H in H1.
apply remove_In in H1.
assumption.
contradiction.
Qed.
Lemma closures_In: forall A (dec : x_dec A) next x xs ys,
- set_In x (closures A dec next xs ys) -> set_In x ys.
+ In x (closures A dec next xs ys) -> In x ys.
Proof.
unfold closures.
induction xs; simpl; intros.
contradiction.
- apply set_union_elim in H.
+ apply union_elim in H.
elim H; intros.
apply closure_In in H0.
assumption.
apply IHxs.
assumption.
Qed.
-Lemma marker_correct: forall A (dec : x_dec A) m1 m2,
- m2 = markerPhase dec m1 -> Marker dec m1 m2.
+Lemma mark_phase_correct: forall A (dec : x_dec A) m1 m2,
+ m2 = mark_phase dec m1 -> MarkPhase dec m1 m2.
Proof.
-unfold markerPhase, Marker.
+unfold mark_phase, MarkPhase.
intros.
destruct m2.
inversion H.
repeat split; auto.
unfold closuresM, marksM, Included.
simpl.
intros.
-unfold marks.
apply filter_dec_In_intro.
unfold In in H0.
apply closures_In in H0.
assumption.
- destruct (set_In_dec dec x).
+ destruct (In_dec dec x).
reflexivity.
contradiction.
Qed.
-Lemma sweeper_correct: forall A (dec : x_dec A) m1 m2,
- m2 = sweeper dec m1 -> Sweeper dec m1 m2.
+Lemma sweep_phase_correct: forall A (dec : x_dec A) m1 m2,
+ m2 = sweep_phase dec m1 -> SweepPhase dec m1 m2.
Proof.
-unfold sweeper, Sweeper.
+unfold sweep_phase, SweepPhase.
intros.
destruct m2; simpl.
inversion H.
repeat split; auto.
Qed.
Theorem gc_correct : forall A (dec : x_dec A) m1 m2,
m2 = gc dec m1 -> GC dec m1 m2.
Proof.
unfold gc, GC.
intros.
-exists (markerPhase dec m1).
+exists (mark_phase dec m1).
split.
- apply marker_correct.
+ apply mark_phase_correct.
reflexivity.
- apply sweeper_correct.
+ apply sweep_phase_correct.
assumption.
Qed.
-Extraction "myGc.ml" markerPhase sweeper gc.
+(** extract *)
+Require Import ExtractUtil.
+Extraction "myGc.ml" gc.
diff --git a/OMakefile b/OMakefile
index 13faed3..7345306 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,30 +1,30 @@
.PHONY: clean doc proof
.DEFAULT: gc_test
# ------------------------------
# Proof part
# ------------------------------
FILES[] =
Util
ExtractUtil
GC
GC_fact
GC_impl
CoqExtract(myGc, $(FILES))
doc: $(addsuffix .v, $(FILES))
mkdir -p doc
- coqdoc -d doc *.v
+ coqdoc --parse-comments --utf8 -d doc *.v
# ------------------------------
# program part
# ------------------------------
OCamlProgram(gc_test, myGc main)
# ------------------------------
# other
# ------------------------------
clean:
rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock *.cmi *.cmo *.cmx *.o gc_test *.opt
diff --git a/main.ml b/main.ml
index d797427..b01230d 100644
--- a/main.ml
+++ b/main.ml
@@ -1,52 +1,52 @@
open MyGc
let assoc xs x =
try
Some (List.assoc x xs)
with Not_found ->
None
let nodes = [ "a"; "b"; "c"; "d"; "e" ];;
let mem = {
roots = [ "a" ];
nodes = nodes;
frees = [];
marker = (fun _ -> Unmarked);
- pointer = (assoc [("a", "e"); ("e", "d")])
+ next = (assoc [("a", "e"); ("e", "d")])
}
let dec x y = x = y;;
let of_list xs =
Printf.sprintf "[ %s ]" (String.concat "; " xs)
let of_marker = function
Marked -> "M"
| Unmarked -> " "
-let of_pointer = function
+let of_next = function
Some n -> Printf.sprintf "-> %s" n
| None -> ""
let show { roots = roots;
nodes = nodes;
frees = frees;
marker = marker;
- pointer = pointer; } =
+ next = next; } =
Printf.sprintf "ROOTS: %s\nFREES: %s\nNODES:\n%s"
(of_list roots)
(of_list frees)
(String.concat "\n" (List.map (fun n ->
Printf.sprintf "%s %s %s"
(of_marker (marker n))
n
- (of_pointer (pointer n)))
+ (of_next (next n)))
nodes))
let _ =
print_endline "=== init ===";
print_endline (show mem);
print_endline "";
print_endline "=== mark ===";
- print_endline (show (markerPhase dec mem));
+ print_endline (show (mark_phase dec mem));
print_endline "";
print_endline "=== sweep ===";
print_endline (show (gc dec mem));
diff --git a/myGc.ml b/myGc.ml
index 8fd0eee..665776d 100644
--- a/myGc.ml
+++ b/myGc.ml
@@ -1,150 +1,170 @@
let __ = let rec f _ = Obj.repr f in Obj.repr f
type 'a sig0 = 'a
(* singleton inductive, whose constructor was exist *)
(** val map : ('a1 -> 'a2) -> 'a1 list -> 'a2 list **)
let rec map f = function
| [] -> []
| a :: t -> (f a) :: (map f t)
(** val fold_right : ('a2 -> 'a1 -> 'a1) -> 'a1 -> 'a2 list -> 'a1 **)
let rec fold_right f a0 = function
| [] -> a0
| b :: t -> f b (fold_right f a0 t)
type 'a set = 'a list
(** val empty_set : 'a1 set **)
let empty_set =
[]
(** val set_add : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set **)
let rec set_add aeq_dec a = function
| [] -> a :: []
| a1 :: x1 ->
if aeq_dec a a1 then a1 :: x1 else a1 :: (set_add aeq_dec a x1)
(** val set_remove : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set **)
let rec set_remove aeq_dec a = function
| [] -> empty_set
| a1 :: x1 -> if aeq_dec a a1 then x1 else a1 :: (set_remove aeq_dec a x1)
(** val set_union : ('a1 -> 'a1 -> bool) -> 'a1 set -> 'a1 set -> 'a1 set **)
let rec set_union aeq_dec x = function
| [] -> x
| a1 :: y1 -> set_add aeq_dec a1 (set_union aeq_dec x y1)
(** val set_In_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> bool **)
let rec set_In_dec aeq_dec a = function
| [] -> false
| a0 :: l -> if aeq_dec a a0 then true else set_In_dec aeq_dec a l
type 'a x_dec = 'a -> 'a -> bool
(** val filter_dec : ('a1 -> bool) -> 'a1 list -> 'a1 list **)
let rec filter_dec dec = function
| [] -> []
| x :: xs -> if dec x then x :: (filter_dec dec xs) else filter_dec dec xs
+(** val in_dec : 'a1 x_dec -> 'a1 -> 'a1 set -> bool **)
+
+let in_dec dec b b0 =
+ set_In_dec dec b b0
+
+(** val union : 'a1 x_dec -> 'a1 set -> 'a1 set -> 'a1 set **)
+
+let union dec b c =
+ set_union dec b c
+
+(** val empty : 'a1 set **)
+
+let empty =
+ empty_set
+
+(** val remove : 'a1 x_dec -> 'a1 -> 'a1 set -> 'a1 set **)
+
+let remove dec b b0 =
+ set_remove dec b b0
+
type mark =
| Marked
| Unmarked
(** val mark_dec : mark -> mark -> bool **)
let mark_dec m1 m2 =
match m1 with
| Marked -> (match m2 with
| Marked -> true
| Unmarked -> false)
| Unmarked -> (match m2 with
| Marked -> false
| Unmarked -> true)
-type 'a mem = { roots : 'a set; nodes : 'a set; frees :
- 'a set; marker : ('a -> mark); pointer :
+type 'a mem = { nodes : 'a set; roots : 'a set; frees :
+ 'a set; marker : ('a -> mark); next :
('a -> 'a option) }
-(** val roots : 'a1 mem -> 'a1 set **)
-
-let roots x = x.roots
-
(** val nodes : 'a1 mem -> 'a1 set **)
let nodes x = x.nodes
+(** val roots : 'a1 mem -> 'a1 set **)
+
+let roots x = x.roots
+
(** val frees : 'a1 mem -> 'a1 set **)
let frees x = x.frees
(** val marker : 'a1 mem -> 'a1 -> mark **)
let marker x = x.marker
-(** val pointer : 'a1 mem -> 'a1 -> 'a1 option **)
+(** val next : 'a1 mem -> 'a1 -> 'a1 option **)
-let pointer x = x.pointer
+let next x = x.next
(** val closure_terminate :
'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set **)
-let rec closure_terminate dec next x = function
- | [] -> empty_set
+let rec closure_terminate dec next0 x = function
+ | [] -> empty
| a :: l ->
- if set_In_dec dec x (a :: l)
- then (match next x with
+ if in_dec dec x (a :: l)
+ then (match next0 x with
| Some y -> x ::
- (Obj.magic (fun _ dec0 next0 x0 xs0 _ ->
- closure_terminate dec0 next0 x0 xs0) __ dec next y
- (set_remove (Obj.magic dec) (Obj.magic x) (a :: l)) __)
- | None -> (Obj.magic x) :: empty_set)
- else empty_set
+ (Obj.magic (fun _ dec0 next1 x0 xs0 _ ->
+ closure_terminate dec0 next1 x0 xs0) __ dec next0 y
+ (remove (Obj.magic dec) (Obj.magic x) (a :: l)) __)
+ | None -> (Obj.magic x) :: empty)
+ else empty
(** val closure :
'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set **)
let closure x0 x1 x2 x3 =
closure_terminate x0 x1 x2 x3
(** val closures :
'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 set -> 'a1 set -> 'a1 set **)
-let closures dec next roots0 nodes0 =
- fold_right (fun x x0 -> set_union dec x x0) empty_set
- (map (fun x -> closure dec next x nodes0) roots0)
+let closures dec next0 roots0 nodes0 =
+ fold_right (fun x x0 -> union dec x x0) empty_set
+ (map (fun x -> closure dec next0 x nodes0) roots0)
(** val closuresM : 'a1 x_dec -> 'a1 mem -> 'a1 set **)
let closuresM dec m =
- closures dec (fun x -> m.pointer x) m.roots m.nodes
+ closures dec (fun x -> m.next x) m.roots m.nodes
-(** val markerPhase : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
+(** val mark_phase : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
-let markerPhase dec m =
- { roots = m.roots; nodes = m.nodes; frees = m.frees; marker = (fun x ->
- if set_In_dec dec x (closuresM dec m) then Marked else Unmarked);
- pointer = (fun x -> m.pointer x) }
+let mark_phase dec m =
+ { nodes = m.nodes; roots = m.roots; frees = m.frees; marker = (fun x ->
+ if in_dec dec x (closuresM dec m) then Marked else Unmarked); next =
+ (fun x -> m.next x) }
-(** val sweeper : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
+(** val sweep_phase : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
-let sweeper dec m =
- { roots = m.roots; nodes = m.nodes; frees =
- (set_union dec m.frees
+let sweep_phase dec m =
+ { nodes = m.nodes; roots = m.roots; frees =
+ (union dec m.frees
(filter_dec (fun n -> mark_dec (m.marker n) Unmarked) m.nodes));
- marker = (fun x -> Unmarked); pointer = (fun x ->
- m.pointer x) }
+ marker = (fun x -> Unmarked); next = (fun x ->
+ m.next x) }
(** val gc : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
let gc dec m =
- sweeper dec (markerPhase dec m)
+ sweep_phase dec (mark_phase dec m)
diff --git a/myGc.mli b/myGc.mli
index 3a5fa4a..72fffbe 100644
--- a/myGc.mli
+++ b/myGc.mli
@@ -1,59 +1,67 @@
type 'a sig0 = 'a
(* singleton inductive, whose constructor was exist *)
val map : ('a1 -> 'a2) -> 'a1 list -> 'a2 list
val fold_right : ('a2 -> 'a1 -> 'a1) -> 'a1 -> 'a2 list -> 'a1
type 'a set = 'a list
val empty_set : 'a1 set
val set_add : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set
val set_remove : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set
val set_union : ('a1 -> 'a1 -> bool) -> 'a1 set -> 'a1 set -> 'a1 set
val set_In_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> bool
type 'a x_dec = 'a -> 'a -> bool
val filter_dec : ('a1 -> bool) -> 'a1 list -> 'a1 list
+val in_dec : 'a1 x_dec -> 'a1 -> 'a1 set -> bool
+
+val union : 'a1 x_dec -> 'a1 set -> 'a1 set -> 'a1 set
+
+val empty : 'a1 set
+
+val remove : 'a1 x_dec -> 'a1 -> 'a1 set -> 'a1 set
+
type mark =
| Marked
| Unmarked
val mark_dec : mark -> mark -> bool
-type 'a mem = { roots : 'a set; nodes : 'a set; frees :
- 'a set; marker : ('a -> mark); pointer :
+type 'a mem = { nodes : 'a set; roots : 'a set; frees :
+ 'a set; marker : ('a -> mark); next :
('a -> 'a option) }
-val roots : 'a1 mem -> 'a1 set
-
val nodes : 'a1 mem -> 'a1 set
+val roots : 'a1 mem -> 'a1 set
+
val frees : 'a1 mem -> 'a1 set
val marker : 'a1 mem -> 'a1 -> mark
-val pointer : 'a1 mem -> 'a1 -> 'a1 option
+val next : 'a1 mem -> 'a1 -> 'a1 option
val closure_terminate :
'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set
val closure : 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set
val closures :
'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 set -> 'a1 set -> 'a1 set
val closuresM : 'a1 x_dec -> 'a1 mem -> 'a1 set
-val markerPhase : 'a1 x_dec -> 'a1 mem -> 'a1 mem
+val mark_phase : 'a1 x_dec -> 'a1 mem -> 'a1 mem
-val sweeper : 'a1 x_dec -> 'a1 mem -> 'a1 mem
+val sweep_phase : 'a1 x_dec -> 'a1 mem -> 'a1 mem
val gc : 'a1 x_dec -> 'a1 mem -> 'a1 mem
|
mzp/GC | 5ca8aafb76ea04a4006cc2a42e433713c61e7d43 | Closureãåé¤ | diff --git a/Closure.v b/Closure.v
deleted file mode 100644
index ea84cc0..0000000
--- a/Closure.v
+++ /dev/null
@@ -1,132 +0,0 @@
-Require Import Lists.ListSet.
-Require Import Lists.List.
-Require Import Util.
-Require Import Recdef.
-
-Lemma remove_dec : forall A (dec : x_dec A) x xs,
- set_In x xs -> length (set_remove dec x xs) < length xs.
-Proof.
-intros.
-induction xs.
- inversion H.
-
- simpl.
- destruct (dec x a).
- apply Lt.lt_n_Sn.
-
- simpl.
- apply Lt.lt_n_S.
- apply IHxs.
- inversion H.
- rewrite H0 in n.
- assert False.
- apply n.
- reflexivity.
-
- contradiction.
-
- apply H0.
-Qed.
-
-Function closure (A : Type) (dec : x_dec A) (next : A -> option A) (x : A) (xs : set A) {measure length xs} : set A :=
- match xs with
- | nil =>
- empty_set A
- | _ =>
- if set_In_dec dec x xs then
- match next x with
- | None => x :: empty_set A
- | Some y => x :: closure A dec next y (set_remove dec x xs)
- end
- else
- empty_set A
- end.
-Proof.
-intros.
-simpl.
-destruct (dec x a).
- apply Lt.lt_n_Sn.
-
- simpl.
- apply Lt.lt_n_S.
- apply remove_dec.
- destruct (set_In_dec dec x (a :: l)).
- inversion s.
- rewrite H in n.
- assert False.
- apply n.
- reflexivity.
- contradiction.
-
- tauto.
-
- discriminate.
-Qed.
-
-Definition closures (A : Type) (dec : x_dec A) (next : A -> option A) (roots : set A) (nodes : set A) : set A :=
- fold_right (set_union dec)
- (empty_set A)
- (map (fun x => closure A dec next x nodes) roots).
-
-
-Lemma remove_In : forall A (dec : x_dec A) x y xs,
- set_In y (set_remove dec x xs) -> set_In y xs.
-Proof.
-induction xs; simpl; intros.
- contradiction.
-
- destruct (dec x a).
- right.
- assumption.
-
- inversion H.
- left.
- assumption.
-
- apply IHxs in H0.
- right.
- assumption.
-Qed.
-
-Lemma closure_In: forall A (dec : x_dec A) next x y xs,
- set_In y (closure A dec next x xs) -> set_In y xs.
-Proof.
-intros until xs.
-pattern x, xs, (closure A dec next x xs).
-apply closure_ind; simpl; intros.
- contradiction.
-
- rewrite <- e.
- decompose [or] H.
- rewrite <- H0.
- assumption.
-
- contradiction.
-
- rewrite <- e.
- decompose [or] H0.
- rewrite <- H1.
- assumption.
-
- apply H in H1.
- apply remove_In in H1.
- assumption.
-
- contradiction.
-Qed.
-
-Lemma closures_In: forall A (dec : x_dec A) next x xs ys,
- set_In x (closures A dec next xs ys) -> set_In x ys.
-Proof.
-unfold closures.
-induction xs; simpl; intros.
- contradiction.
-
- apply set_union_elim in H.
- elim H; intros.
- apply closure_In in H0.
- assumption.
-
- apply IHxs.
- assumption.
-Qed.
\ No newline at end of file
diff --git a/GC.v b/GC.v
index 0cc55b6..3617acf 100644
--- a/GC.v
+++ b/GC.v
@@ -1,75 +1,130 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
-Require Import Closure.
+Require Import Recdef.
(** * operations of set *)
Definition In {A : Type} (elem : A) (sets : set A) :=
set_In elem sets.
Definition Included {A : Type} (B C : set A) : Prop :=
forall x, In x B -> In x C.
Definition Union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
set_union dec B C.
(** * Memory *)
Inductive mark :=
| Marked : mark
| Unmarked : mark.
Definition mark_dec : forall (m1 m2 : mark), { m1 = m2} + { m1 <> m2}.
Proof.
decide equality.
Qed.
Record Mem {A : Type} := mkMem {
roots : set A; (** root objects *)
nodes : set A; (** all objects in memory *)
frees : set A; (** free list *)
marker : A -> mark; (** get mark of the object *)
pointer : A -> option A (** get next object of the object *)
}.
-Lemma destruct_mem : forall A m,
- m = mkMem A (roots m) (nodes m) (frees m) (marker m) (pointer m).
+(** * GC *)
+
+(** ** closure *)
+Lemma remove_dec : forall A (dec : x_dec A) x xs,
+ set_In x xs -> length (set_remove dec x xs) < length xs.
Proof.
intros.
-destruct m.
-simpl.
-reflexivity.
+induction xs.
+ inversion H.
+
+ simpl.
+ destruct (dec x a).
+ apply Lt.lt_n_Sn.
+
+ simpl.
+ apply Lt.lt_n_S.
+ apply IHxs.
+ inversion H.
+ rewrite H0 in n.
+ assert False.
+ apply n.
+ reflexivity.
+
+ contradiction.
+
+ apply H0.
Qed.
+Function closure (A : Type) (dec : x_dec A) (next : A -> option A) (x : A) (xs : set A) {measure length xs} : set A :=
+ match xs with
+ | nil =>
+ empty_set A
+ | _ =>
+ if set_In_dec dec x xs then
+ match next x with
+ | None => x :: empty_set A
+ | Some y => x :: closure A dec next y (set_remove dec x xs)
+ end
+ else
+ empty_set A
+ end.
+Proof.
+intros.
+simpl.
+destruct (dec x a).
+ apply Lt.lt_n_Sn.
-(** * GC *)
+ simpl.
+ apply Lt.lt_n_S.
+ apply remove_dec.
+ destruct (set_In_dec dec x (a :: l)).
+ inversion s.
+ rewrite H in n.
+ assert False.
+ apply n.
+ reflexivity.
+ contradiction.
+
+ tauto.
+
+ discriminate.
+Qed.
+
+Definition closures (A : Type) (dec : x_dec A) (next : A -> option A) (roots : set A) (nodes : set A) : set A :=
+ fold_right (set_union dec)
+ (empty_set A)
+ (map (fun x => closure A dec next x nodes) roots).
-(** ** closure *)
Definition closuresM {A : Type} (dec : x_dec A) (m : Mem) :=
closures A dec (pointer m) (roots m) (nodes m).
(** ** Marker utility *)
Definition marks (A : Type) (marker : A -> mark) (ma : mark) (xs : set A) : set A :=
filter_dec (fun x => mark_dec (marker x) ma) xs.
Definition marksM {A : Type} (ma : mark) (m : Mem) :=
marks A (marker m) ma (nodes m).
(** ** main GC *)
(** marker *)
Definition Marker {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
frees m1 = frees m2 /\
pointer m1 = pointer m2 /\
Included (closuresM dec m2) (marksM Marked m2).
(** sweeper *)
Definition Sweeper {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
pointer m1 = pointer m2 /\
frees m2 = Union dec (frees m1) (marksM Unmarked m1) /\
forall (n : A), In n (nodes m2) -> marker m2 n = Unmarked.
(** mark & sweep GC *)
Definition GC {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) := exists m : Mem,
Marker dec m1 m /\ Sweeper dec m m2.
diff --git a/GC_impl.v b/GC_impl.v
index be572fe..7b7c448 100644
--- a/GC_impl.v
+++ b/GC_impl.v
@@ -1,75 +1,137 @@
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import GC.
-Require Import Closure.
Require Import Util.
Require Import ExtractUtil.
Definition markerPhase {A : Type} (dec : x_dec A) (m : Mem) :=
let marks :=
closuresM dec m
in
mkMem A (roots m)
(nodes m)
(frees m)
(fun x => if set_In_dec dec x marks then Marked else Unmarked)
(pointer m).
Definition sweeper {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
mkMem A (roots m)
(nodes m)
(set_union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Unmarked) @@ nodes m))
(fun _ => Unmarked)
(pointer m).
Definition gc {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
sweeper dec (markerPhase dec m).
+
+Lemma remove_In : forall A (dec : x_dec A) x y xs,
+ set_In y (set_remove dec x xs) -> set_In y xs.
+Proof.
+induction xs; simpl; intros.
+ contradiction.
+
+ destruct (dec x a).
+ right.
+ assumption.
+
+ inversion H.
+ left.
+ assumption.
+
+ apply IHxs in H0.
+ right.
+ assumption.
+Qed.
+
+Lemma closure_In: forall A (dec : x_dec A) next x y xs,
+ set_In y (closure A dec next x xs) -> set_In y xs.
+Proof.
+intros until xs.
+pattern x, xs, (closure A dec next x xs).
+apply closure_ind; simpl; intros.
+ contradiction.
+
+ rewrite <- e.
+ decompose [or] H.
+ rewrite <- H0.
+ assumption.
+
+ contradiction.
+
+ rewrite <- e.
+ decompose [or] H0.
+ rewrite <- H1.
+ assumption.
+
+ apply H in H1.
+ apply remove_In in H1.
+ assumption.
+
+ contradiction.
+Qed.
+
+Lemma closures_In: forall A (dec : x_dec A) next x xs ys,
+ set_In x (closures A dec next xs ys) -> set_In x ys.
+Proof.
+unfold closures.
+induction xs; simpl; intros.
+ contradiction.
+
+ apply set_union_elim in H.
+ elim H; intros.
+ apply closure_In in H0.
+ assumption.
+
+ apply IHxs.
+ assumption.
+Qed.
+
Lemma marker_correct: forall A (dec : x_dec A) m1 m2,
m2 = markerPhase dec m1 -> Marker dec m1 m2.
Proof.
unfold markerPhase, Marker.
intros.
destruct m2.
inversion H.
repeat split; auto.
unfold closuresM, marksM, Included.
simpl.
intros.
unfold marks.
apply filter_dec_In_intro.
unfold In in H0.
apply closures_In in H0.
assumption.
destruct (set_In_dec dec x).
reflexivity.
contradiction.
Qed.
Lemma sweeper_correct: forall A (dec : x_dec A) m1 m2,
m2 = sweeper dec m1 -> Sweeper dec m1 m2.
Proof.
unfold sweeper, Sweeper.
intros.
destruct m2; simpl.
inversion H.
repeat split; auto.
Qed.
Theorem gc_correct : forall A (dec : x_dec A) m1 m2,
m2 = gc dec m1 -> GC dec m1 m2.
Proof.
unfold gc, GC.
intros.
exists (markerPhase dec m1).
split.
apply marker_correct.
reflexivity.
apply sweeper_correct.
assumption.
Qed.
Extraction "myGc.ml" markerPhase sweeper gc.
diff --git a/OMakefile b/OMakefile
index 87198aa..13faed3 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,31 +1,30 @@
.PHONY: clean doc proof
.DEFAULT: gc_test
# ------------------------------
# Proof part
# ------------------------------
FILES[] =
Util
ExtractUtil
- Closure
GC
GC_fact
GC_impl
CoqExtract(myGc, $(FILES))
doc: $(addsuffix .v, $(FILES))
mkdir -p doc
coqdoc -d doc *.v
# ------------------------------
# program part
# ------------------------------
OCamlProgram(gc_test, myGc main)
# ------------------------------
# other
# ------------------------------
clean:
rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock *.cmi *.cmo *.cmx *.o gc_test *.opt
diff --git a/myGc.ml b/myGc.ml
index 5d24487..8fd0eee 100644
--- a/myGc.ml
+++ b/myGc.ml
@@ -1,150 +1,150 @@
let __ = let rec f _ = Obj.repr f in Obj.repr f
type 'a sig0 = 'a
(* singleton inductive, whose constructor was exist *)
(** val map : ('a1 -> 'a2) -> 'a1 list -> 'a2 list **)
let rec map f = function
| [] -> []
| a :: t -> (f a) :: (map f t)
(** val fold_right : ('a2 -> 'a1 -> 'a1) -> 'a1 -> 'a2 list -> 'a1 **)
let rec fold_right f a0 = function
| [] -> a0
| b :: t -> f b (fold_right f a0 t)
type 'a set = 'a list
(** val empty_set : 'a1 set **)
let empty_set =
[]
(** val set_add : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set **)
let rec set_add aeq_dec a = function
| [] -> a :: []
| a1 :: x1 ->
if aeq_dec a a1 then a1 :: x1 else a1 :: (set_add aeq_dec a x1)
(** val set_remove : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set **)
let rec set_remove aeq_dec a = function
| [] -> empty_set
| a1 :: x1 -> if aeq_dec a a1 then x1 else a1 :: (set_remove aeq_dec a x1)
(** val set_union : ('a1 -> 'a1 -> bool) -> 'a1 set -> 'a1 set -> 'a1 set **)
let rec set_union aeq_dec x = function
| [] -> x
| a1 :: y1 -> set_add aeq_dec a1 (set_union aeq_dec x y1)
(** val set_In_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> bool **)
let rec set_In_dec aeq_dec a = function
| [] -> false
| a0 :: l -> if aeq_dec a a0 then true else set_In_dec aeq_dec a l
type 'a x_dec = 'a -> 'a -> bool
(** val filter_dec : ('a1 -> bool) -> 'a1 list -> 'a1 list **)
let rec filter_dec dec = function
| [] -> []
| x :: xs -> if dec x then x :: (filter_dec dec xs) else filter_dec dec xs
-(** val closure_terminate :
- 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set **)
-
-let rec closure_terminate dec next x = function
- | [] -> empty_set
- | a :: l ->
- if set_In_dec dec x (a :: l)
- then (match next x with
- | Some y -> x ::
- (Obj.magic (fun _ dec0 next0 x0 xs0 _ ->
- closure_terminate dec0 next0 x0 xs0) __ dec next y
- (set_remove (Obj.magic dec) (Obj.magic x) (a :: l)) __)
- | None -> (Obj.magic x) :: empty_set)
- else empty_set
-
-(** val closure :
- 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set **)
-
-let closure x0 x1 x2 x3 =
- closure_terminate x0 x1 x2 x3
-
-(** val closures :
- 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 set -> 'a1 set -> 'a1 set **)
-
-let closures dec next roots0 nodes0 =
- fold_right (fun x x0 -> set_union dec x x0) empty_set
- (map (fun x -> closure dec next x nodes0) roots0)
-
type mark =
| Marked
| Unmarked
(** val mark_dec : mark -> mark -> bool **)
let mark_dec m1 m2 =
match m1 with
| Marked -> (match m2 with
| Marked -> true
| Unmarked -> false)
| Unmarked -> (match m2 with
| Marked -> false
| Unmarked -> true)
type 'a mem = { roots : 'a set; nodes : 'a set; frees :
'a set; marker : ('a -> mark); pointer :
('a -> 'a option) }
(** val roots : 'a1 mem -> 'a1 set **)
let roots x = x.roots
(** val nodes : 'a1 mem -> 'a1 set **)
let nodes x = x.nodes
(** val frees : 'a1 mem -> 'a1 set **)
let frees x = x.frees
(** val marker : 'a1 mem -> 'a1 -> mark **)
let marker x = x.marker
(** val pointer : 'a1 mem -> 'a1 -> 'a1 option **)
let pointer x = x.pointer
+(** val closure_terminate :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set **)
+
+let rec closure_terminate dec next x = function
+ | [] -> empty_set
+ | a :: l ->
+ if set_In_dec dec x (a :: l)
+ then (match next x with
+ | Some y -> x ::
+ (Obj.magic (fun _ dec0 next0 x0 xs0 _ ->
+ closure_terminate dec0 next0 x0 xs0) __ dec next y
+ (set_remove (Obj.magic dec) (Obj.magic x) (a :: l)) __)
+ | None -> (Obj.magic x) :: empty_set)
+ else empty_set
+
+(** val closure :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set **)
+
+let closure x0 x1 x2 x3 =
+ closure_terminate x0 x1 x2 x3
+
+(** val closures :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 set -> 'a1 set -> 'a1 set **)
+
+let closures dec next roots0 nodes0 =
+ fold_right (fun x x0 -> set_union dec x x0) empty_set
+ (map (fun x -> closure dec next x nodes0) roots0)
+
(** val closuresM : 'a1 x_dec -> 'a1 mem -> 'a1 set **)
let closuresM dec m =
closures dec (fun x -> m.pointer x) m.roots m.nodes
(** val markerPhase : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
let markerPhase dec m =
{ roots = m.roots; nodes = m.nodes; frees = m.frees; marker = (fun x ->
if set_In_dec dec x (closuresM dec m) then Marked else Unmarked);
pointer = (fun x -> m.pointer x) }
(** val sweeper : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
let sweeper dec m =
{ roots = m.roots; nodes = m.nodes; frees =
(set_union dec m.frees
(filter_dec (fun n -> mark_dec (m.marker n) Unmarked) m.nodes));
marker = (fun x -> Unmarked); pointer = (fun x ->
m.pointer x) }
(** val gc : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
let gc dec m =
sweeper dec (markerPhase dec m)
diff --git a/myGc.mli b/myGc.mli
index 3dabf7d..3a5fa4a 100644
--- a/myGc.mli
+++ b/myGc.mli
@@ -1,59 +1,59 @@
type 'a sig0 = 'a
(* singleton inductive, whose constructor was exist *)
val map : ('a1 -> 'a2) -> 'a1 list -> 'a2 list
val fold_right : ('a2 -> 'a1 -> 'a1) -> 'a1 -> 'a2 list -> 'a1
type 'a set = 'a list
val empty_set : 'a1 set
val set_add : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set
val set_remove : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set
val set_union : ('a1 -> 'a1 -> bool) -> 'a1 set -> 'a1 set -> 'a1 set
val set_In_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> bool
type 'a x_dec = 'a -> 'a -> bool
val filter_dec : ('a1 -> bool) -> 'a1 list -> 'a1 list
-val closure_terminate :
- 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set
-
-val closure : 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set
-
-val closures :
- 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 set -> 'a1 set -> 'a1 set
-
type mark =
| Marked
| Unmarked
val mark_dec : mark -> mark -> bool
type 'a mem = { roots : 'a set; nodes : 'a set; frees :
'a set; marker : ('a -> mark); pointer :
('a -> 'a option) }
val roots : 'a1 mem -> 'a1 set
val nodes : 'a1 mem -> 'a1 set
val frees : 'a1 mem -> 'a1 set
val marker : 'a1 mem -> 'a1 -> mark
val pointer : 'a1 mem -> 'a1 -> 'a1 option
+val closure_terminate :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set
+
+val closure : 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set
+
+val closures :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 set -> 'a1 set -> 'a1 set
+
val closuresM : 'a1 x_dec -> 'a1 mem -> 'a1 set
val markerPhase : 'a1 x_dec -> 'a1 mem -> 'a1 mem
val sweeper : 'a1 x_dec -> 'a1 mem -> 'a1 mem
val gc : 'a1 x_dec -> 'a1 mem -> 'a1 mem
|
mzp/GC | cfa616c90dc308dbe88ee8231daca5962d7b05ad | extractã§ããããã«ãã | diff --git a/.gitignore b/.gitignore
index c627568..283ae49 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,11 +1,15 @@
*.vo
*.glob
*~
*.omc
.omakedb
.omakedb.lock
*.html
*.css
*.swp
*.png
-*.dot
\ No newline at end of file
+*.dot
+*.cm[iox]
+*.o
+gc_test
+*.opt
\ No newline at end of file
diff --git a/CoqBuildRule b/CoqBuildRule
index 78e12a5..0537cf6 100644
--- a/CoqBuildRule
+++ b/CoqBuildRule
@@ -1,14 +1,18 @@
public.COQC = coqc
public.COQC_FLAGS =
public.COQLIB = $(shell coqc -where)/
public.COQDEP = coqdep -w -coqlib $`(COQLIB) -I .
public.CoqProof(files) =
vo=$(addsuffix .vo,$(files))
value $(vo)
+public.CoqExtract(targets, files) =
+ export
+ $(addsuffix .ml, $(targets)) $(addsuffix .mli, $(targets)) : $(addsuffix .vo,$(files))
+
%.vo %.glob: %.v
$(COQC) $(COQC_FLAGS) $<
.SCANNER: %.vo: %.v
$(COQDEP) $<
diff --git a/ExtractUtil.v b/ExtractUtil.v
new file mode 100644
index 0000000..f1bad3e
--- /dev/null
+++ b/ExtractUtil.v
@@ -0,0 +1,94 @@
+Require Ascii.
+Require String.
+Require List.
+
+(* basic types for OCaml *)
+Parameter mlunit mlchar mlint mlstring : Set.
+
+(* unit *)
+Extract Constant mlunit => "unit".
+
+(* bool *)
+Extract Inductive bool => "bool" ["true" "false"].
+Extract Inductive sumbool => "bool" ["true" "false"].
+
+(* int *)
+Extract Constant mlint => "int".
+Parameter mlint_of_nat : nat -> mlint.
+Parameter nat_of_mlint : mlint -> nat.
+Extract Constant mlint_of_nat =>
+ "let rec iter = function O -> 0 | S p -> succ (iter p) in iter".
+Extract Constant nat_of_mlint =>
+ "let rec iter = function 0 -> O | n -> S (iter (pred n)) in iter".
+
+(* char *)
+Extract Constant mlchar => "char".
+Parameter mlchar_of_mlint : mlint -> mlchar.
+Parameter mlint_of_mlchar : mlchar -> mlint.
+Extract Constant mlchar_of_mlint => "char_of_int".
+Extract Constant mlint_of_mlchar => "int_of_char".
+
+(* list *)
+Extract Inductive List.list => "list" ["[]" "(::)"].
+
+(* option *)
+Extract Inductive option => "option" ["Some" "None"].
+
+(* string *)
+Extract Constant mlstring => "string".
+Extract Inductive String.string => "ascii list" ["[]" "(::)"].
+Parameter string_of_list : List.list Ascii.ascii -> String.string.
+Parameter list_of_string : String.string -> List.list Ascii.ascii.
+Extract Constant list_of_string => "(fun x -> x)".
+Extract Constant string_of_list => "(fun x -> x)".
+
+Parameter mlstring_of_list : forall {A:Type},
+ (A->mlchar) -> List.list A -> mlstring.
+Parameter list_of_mlstring : forall {A:Type},
+ (mlchar->A) -> mlstring -> List.list A.
+Extract Constant mlstring_of_list =>
+ "(fun f s -> String.concat """"
+ (List.map (fun x -> String.make 1 (f x)) s))".
+Extract Constant list_of_mlstring => "
+(fun f s ->
+ let rec explode_rec n =
+ if n >= String.length s then
+ []
+ else
+ f (String.get s n) :: explode_rec (succ n)
+ in
+ explode_rec 0)
+".
+
+Parameter mlstring_of_mlint : mlint -> mlstring.
+Extract Constant mlstring_of_mlint => "string_of_int".
+
+
+(* print to stdout *)
+Parameter print_mlstring : mlstring -> mlunit.
+Parameter println_mlstring : mlstring -> mlunit.
+Parameter prerr_mlstring : mlstring -> mlunit.
+Parameter prerrln_mlstring : mlstring -> mlunit.
+Parameter semicolon_flipped : forall {A:Type}, A -> mlunit -> A.
+Extract Constant semicolon_flipped => "(fun x f -> f; x)".
+Extract Constant print_mlstring => "print_string".
+Extract Constant println_mlstring => "print_endline".
+Extract Constant prerr_mlstring => "print_string".
+Extract Constant prerrln_mlstring => "print_endline".
+
+CoInductive llist (A: Type) : Type :=
+ LNil | LCons (x: A) (xs: llist A).
+
+Implicit Arguments LNil [A].
+Implicit Arguments LCons [A].
+
+Parameter get_contents_mlchars : llist mlchar.
+Extract Constant get_contents_mlchars => "
+ let rec iter store =
+ lazy
+ begin
+ try (LCons (input_char stdin, iter())) with
+ | End_of_file -> LNil
+ end
+ in
+ iter ()".
diff --git a/GC_impl.v b/GC_impl.v
index 8826056..be572fe 100644
--- a/GC_impl.v
+++ b/GC_impl.v
@@ -1,56 +1,75 @@
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import GC.
Require Import Closure.
Require Import Util.
+Require Import ExtractUtil.
-Definition marker {A : Type} (dec : x_dec A) (m : Mem) :=
+Definition markerPhase {A : Type} (dec : x_dec A) (m : Mem) :=
let marks :=
closuresM dec m
in
mkMem A (roots m)
(nodes m)
(frees m)
(fun x => if set_In_dec dec x marks then Marked else Unmarked)
(pointer m).
Definition sweeper {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
mkMem A (roots m)
(nodes m)
(set_union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Unmarked) @@ nodes m))
(fun _ => Unmarked)
(pointer m).
-Theorem marker_correct: forall A (dec : x_dec A) m1 m2,
- m2 = marker dec m1 -> Marker dec m1 m2.
+Definition gc {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
+ sweeper dec (markerPhase dec m).
+
+Lemma marker_correct: forall A (dec : x_dec A) m1 m2,
+ m2 = markerPhase dec m1 -> Marker dec m1 m2.
Proof.
-unfold marker, Marker.
+unfold markerPhase, Marker.
intros.
destruct m2.
inversion H.
repeat split; auto.
unfold closuresM, marksM, Included.
simpl.
intros.
unfold marks.
apply filter_dec_In_intro.
unfold In in H0.
apply closures_In in H0.
assumption.
destruct (set_In_dec dec x).
reflexivity.
contradiction.
Qed.
-Theorem sweeper_correct: forall A (dec : x_dec A) m1 m2,
+Lemma sweeper_correct: forall A (dec : x_dec A) m1 m2,
m2 = sweeper dec m1 -> Sweeper dec m1 m2.
Proof.
unfold sweeper, Sweeper.
intros.
destruct m2; simpl.
inversion H.
repeat split; auto.
Qed.
+Theorem gc_correct : forall A (dec : x_dec A) m1 m2,
+ m2 = gc dec m1 -> GC dec m1 m2.
+Proof.
+unfold gc, GC.
+intros.
+exists (markerPhase dec m1).
+split.
+ apply marker_correct.
+ reflexivity.
+
+ apply sweeper_correct.
+ assumption.
+Qed.
+
+Extraction "myGc.ml" markerPhase sweeper gc.
diff --git a/OMakefile b/OMakefile
index 16fc43a..87198aa 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,19 +1,31 @@
+.PHONY: clean doc proof
+.DEFAULT: gc_test
+# ------------------------------
+# Proof part
+# ------------------------------
FILES[] =
Util
+ ExtractUtil
Closure
GC
GC_fact
GC_impl
-.PHONY: clean graph doc all
-.DEFAULT: all
-
-all: $(CoqProof $(FILES))
-
-clean:
- rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock
+CoqExtract(myGc, $(FILES))
doc: $(addsuffix .v, $(FILES))
mkdir -p doc
coqdoc -d doc *.v
+# ------------------------------
+# program part
+# ------------------------------
+OCamlProgram(gc_test, myGc main)
+
+# ------------------------------
+# other
+# ------------------------------
+clean:
+ rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock *.cmi *.cmo *.cmx *.o gc_test *.opt
+
+
diff --git a/OMakeroot b/OMakeroot
index 8b6e763..764b369 100644
--- a/OMakeroot
+++ b/OMakeroot
@@ -1,5 +1,6 @@
DefineCommandVars()
open CoqBuildRule
+open build/OCaml
.SUBDIRS: .
diff --git a/main.ml b/main.ml
new file mode 100644
index 0000000..d797427
--- /dev/null
+++ b/main.ml
@@ -0,0 +1,52 @@
+open MyGc
+let assoc xs x =
+ try
+ Some (List.assoc x xs)
+ with Not_found ->
+ None
+
+let nodes = [ "a"; "b"; "c"; "d"; "e" ];;
+let mem = {
+ roots = [ "a" ];
+ nodes = nodes;
+ frees = [];
+ marker = (fun _ -> Unmarked);
+ pointer = (assoc [("a", "e"); ("e", "d")])
+}
+
+let dec x y = x = y;;
+
+let of_list xs =
+ Printf.sprintf "[ %s ]" (String.concat "; " xs)
+
+let of_marker = function
+ Marked -> "M"
+ | Unmarked -> " "
+
+let of_pointer = function
+ Some n -> Printf.sprintf "-> %s" n
+ | None -> ""
+
+let show { roots = roots;
+ nodes = nodes;
+ frees = frees;
+ marker = marker;
+ pointer = pointer; } =
+ Printf.sprintf "ROOTS: %s\nFREES: %s\nNODES:\n%s"
+ (of_list roots)
+ (of_list frees)
+ (String.concat "\n" (List.map (fun n ->
+ Printf.sprintf "%s %s %s"
+ (of_marker (marker n))
+ n
+ (of_pointer (pointer n)))
+ nodes))
+let _ =
+ print_endline "=== init ===";
+ print_endline (show mem);
+ print_endline "";
+ print_endline "=== mark ===";
+ print_endline (show (markerPhase dec mem));
+ print_endline "";
+ print_endline "=== sweep ===";
+ print_endline (show (gc dec mem));
diff --git a/myGc.ml b/myGc.ml
new file mode 100644
index 0000000..5d24487
--- /dev/null
+++ b/myGc.ml
@@ -0,0 +1,150 @@
+let __ = let rec f _ = Obj.repr f in Obj.repr f
+
+type 'a sig0 = 'a
+ (* singleton inductive, whose constructor was exist *)
+
+(** val map : ('a1 -> 'a2) -> 'a1 list -> 'a2 list **)
+
+let rec map f = function
+ | [] -> []
+ | a :: t -> (f a) :: (map f t)
+
+(** val fold_right : ('a2 -> 'a1 -> 'a1) -> 'a1 -> 'a2 list -> 'a1 **)
+
+let rec fold_right f a0 = function
+ | [] -> a0
+ | b :: t -> f b (fold_right f a0 t)
+
+type 'a set = 'a list
+
+(** val empty_set : 'a1 set **)
+
+let empty_set =
+ []
+
+(** val set_add : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set **)
+
+let rec set_add aeq_dec a = function
+ | [] -> a :: []
+ | a1 :: x1 ->
+ if aeq_dec a a1 then a1 :: x1 else a1 :: (set_add aeq_dec a x1)
+
+(** val set_remove : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set **)
+
+let rec set_remove aeq_dec a = function
+ | [] -> empty_set
+ | a1 :: x1 -> if aeq_dec a a1 then x1 else a1 :: (set_remove aeq_dec a x1)
+
+(** val set_union : ('a1 -> 'a1 -> bool) -> 'a1 set -> 'a1 set -> 'a1 set **)
+
+let rec set_union aeq_dec x = function
+ | [] -> x
+ | a1 :: y1 -> set_add aeq_dec a1 (set_union aeq_dec x y1)
+
+(** val set_In_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> bool **)
+
+let rec set_In_dec aeq_dec a = function
+ | [] -> false
+ | a0 :: l -> if aeq_dec a a0 then true else set_In_dec aeq_dec a l
+
+type 'a x_dec = 'a -> 'a -> bool
+
+(** val filter_dec : ('a1 -> bool) -> 'a1 list -> 'a1 list **)
+
+let rec filter_dec dec = function
+ | [] -> []
+ | x :: xs -> if dec x then x :: (filter_dec dec xs) else filter_dec dec xs
+
+(** val closure_terminate :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set **)
+
+let rec closure_terminate dec next x = function
+ | [] -> empty_set
+ | a :: l ->
+ if set_In_dec dec x (a :: l)
+ then (match next x with
+ | Some y -> x ::
+ (Obj.magic (fun _ dec0 next0 x0 xs0 _ ->
+ closure_terminate dec0 next0 x0 xs0) __ dec next y
+ (set_remove (Obj.magic dec) (Obj.magic x) (a :: l)) __)
+ | None -> (Obj.magic x) :: empty_set)
+ else empty_set
+
+(** val closure :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set **)
+
+let closure x0 x1 x2 x3 =
+ closure_terminate x0 x1 x2 x3
+
+(** val closures :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 set -> 'a1 set -> 'a1 set **)
+
+let closures dec next roots0 nodes0 =
+ fold_right (fun x x0 -> set_union dec x x0) empty_set
+ (map (fun x -> closure dec next x nodes0) roots0)
+
+type mark =
+ | Marked
+ | Unmarked
+
+(** val mark_dec : mark -> mark -> bool **)
+
+let mark_dec m1 m2 =
+ match m1 with
+ | Marked -> (match m2 with
+ | Marked -> true
+ | Unmarked -> false)
+ | Unmarked -> (match m2 with
+ | Marked -> false
+ | Unmarked -> true)
+
+type 'a mem = { roots : 'a set; nodes : 'a set; frees :
+ 'a set; marker : ('a -> mark); pointer :
+ ('a -> 'a option) }
+
+(** val roots : 'a1 mem -> 'a1 set **)
+
+let roots x = x.roots
+
+(** val nodes : 'a1 mem -> 'a1 set **)
+
+let nodes x = x.nodes
+
+(** val frees : 'a1 mem -> 'a1 set **)
+
+let frees x = x.frees
+
+(** val marker : 'a1 mem -> 'a1 -> mark **)
+
+let marker x = x.marker
+
+(** val pointer : 'a1 mem -> 'a1 -> 'a1 option **)
+
+let pointer x = x.pointer
+
+(** val closuresM : 'a1 x_dec -> 'a1 mem -> 'a1 set **)
+
+let closuresM dec m =
+ closures dec (fun x -> m.pointer x) m.roots m.nodes
+
+(** val markerPhase : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
+
+let markerPhase dec m =
+ { roots = m.roots; nodes = m.nodes; frees = m.frees; marker = (fun x ->
+ if set_In_dec dec x (closuresM dec m) then Marked else Unmarked);
+ pointer = (fun x -> m.pointer x) }
+
+(** val sweeper : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
+
+let sweeper dec m =
+ { roots = m.roots; nodes = m.nodes; frees =
+ (set_union dec m.frees
+ (filter_dec (fun n -> mark_dec (m.marker n) Unmarked) m.nodes));
+ marker = (fun x -> Unmarked); pointer = (fun x ->
+ m.pointer x) }
+
+(** val gc : 'a1 x_dec -> 'a1 mem -> 'a1 mem **)
+
+let gc dec m =
+ sweeper dec (markerPhase dec m)
+
diff --git a/myGc.mli b/myGc.mli
new file mode 100644
index 0000000..3dabf7d
--- /dev/null
+++ b/myGc.mli
@@ -0,0 +1,59 @@
+type 'a sig0 = 'a
+ (* singleton inductive, whose constructor was exist *)
+
+val map : ('a1 -> 'a2) -> 'a1 list -> 'a2 list
+
+val fold_right : ('a2 -> 'a1 -> 'a1) -> 'a1 -> 'a2 list -> 'a1
+
+type 'a set = 'a list
+
+val empty_set : 'a1 set
+
+val set_add : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set
+
+val set_remove : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> 'a1 set
+
+val set_union : ('a1 -> 'a1 -> bool) -> 'a1 set -> 'a1 set -> 'a1 set
+
+val set_In_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 set -> bool
+
+type 'a x_dec = 'a -> 'a -> bool
+
+val filter_dec : ('a1 -> bool) -> 'a1 list -> 'a1 list
+
+val closure_terminate :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set
+
+val closure : 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 -> 'a1 set -> 'a1 set
+
+val closures :
+ 'a1 x_dec -> ('a1 -> 'a1 option) -> 'a1 set -> 'a1 set -> 'a1 set
+
+type mark =
+ | Marked
+ | Unmarked
+
+val mark_dec : mark -> mark -> bool
+
+type 'a mem = { roots : 'a set; nodes : 'a set; frees :
+ 'a set; marker : ('a -> mark); pointer :
+ ('a -> 'a option) }
+
+val roots : 'a1 mem -> 'a1 set
+
+val nodes : 'a1 mem -> 'a1 set
+
+val frees : 'a1 mem -> 'a1 set
+
+val marker : 'a1 mem -> 'a1 -> mark
+
+val pointer : 'a1 mem -> 'a1 -> 'a1 option
+
+val closuresM : 'a1 x_dec -> 'a1 mem -> 'a1 set
+
+val markerPhase : 'a1 x_dec -> 'a1 mem -> 'a1 mem
+
+val sweeper : 'a1 x_dec -> 'a1 mem -> 'a1 mem
+
+val gc : 'a1 x_dec -> 'a1 mem -> 'a1 mem
+
|
mzp/GC | b83b6e226953490889bfd1f51a0c215058c6d5da | sweeperã®æ£å½æ§ã証æãã | diff --git a/GC_impl.v b/GC_impl.v
index 4181048..8826056 100644
--- a/GC_impl.v
+++ b/GC_impl.v
@@ -1,45 +1,56 @@
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import GC.
Require Import Closure.
Require Import Util.
Definition marker {A : Type} (dec : x_dec A) (m : Mem) :=
let marks :=
closuresM dec m
in
mkMem A (roots m)
(nodes m)
(frees m)
(fun x => if set_In_dec dec x marks then Marked else Unmarked)
(pointer m).
Definition sweeper {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
mkMem A (roots m)
(nodes m)
- (set_union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Marked) @@ nodes m))
+ (set_union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Unmarked) @@ nodes m))
(fun _ => Unmarked)
(pointer m).
Theorem marker_correct: forall A (dec : x_dec A) m1 m2,
m2 = marker dec m1 -> Marker dec m1 m2.
Proof.
unfold marker, Marker.
intros.
destruct m2.
inversion H.
repeat split; auto.
unfold closuresM, marksM, Included.
simpl.
intros.
unfold marks.
apply filter_dec_In_intro.
unfold In in H0.
apply closures_In in H0.
assumption.
destruct (set_In_dec dec x).
reflexivity.
contradiction.
Qed.
+
+Theorem sweeper_correct: forall A (dec : x_dec A) m1 m2,
+ m2 = sweeper dec m1 -> Sweeper dec m1 m2.
+Proof.
+unfold sweeper, Sweeper.
+intros.
+destruct m2; simpl.
+inversion H.
+repeat split; auto.
+Qed.
+
|
mzp/GC | 1adc02c806fcf79d6470ef4412d989e73c65ef2e | markerã®å®è£
ãæ£ãã証æããã | diff --git a/Closure.v b/Closure.v
index 352cad6..ea84cc0 100644
--- a/Closure.v
+++ b/Closure.v
@@ -1,132 +1,132 @@
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
Require Import Recdef.
Lemma remove_dec : forall A (dec : x_dec A) x xs,
set_In x xs -> length (set_remove dec x xs) < length xs.
Proof.
intros.
induction xs.
inversion H.
simpl.
destruct (dec x a).
apply Lt.lt_n_Sn.
simpl.
apply Lt.lt_n_S.
apply IHxs.
inversion H.
rewrite H0 in n.
assert False.
apply n.
reflexivity.
contradiction.
apply H0.
Qed.
Function closure (A : Type) (dec : x_dec A) (next : A -> option A) (x : A) (xs : set A) {measure length xs} : set A :=
match xs with
| nil =>
empty_set A
| _ =>
if set_In_dec dec x xs then
match next x with
| None => x :: empty_set A
| Some y => x :: closure A dec next y (set_remove dec x xs)
end
else
empty_set A
end.
Proof.
intros.
simpl.
destruct (dec x a).
apply Lt.lt_n_Sn.
simpl.
apply Lt.lt_n_S.
apply remove_dec.
destruct (set_In_dec dec x (a :: l)).
inversion s.
rewrite H in n.
assert False.
apply n.
reflexivity.
contradiction.
tauto.
discriminate.
Qed.
Definition closures (A : Type) (dec : x_dec A) (next : A -> option A) (roots : set A) (nodes : set A) : set A :=
fold_right (set_union dec)
(empty_set A)
(map (fun x => closure A dec next x nodes) roots).
Lemma remove_In : forall A (dec : x_dec A) x y xs,
set_In y (set_remove dec x xs) -> set_In y xs.
Proof.
induction xs; simpl; intros.
contradiction.
destruct (dec x a).
right.
assumption.
inversion H.
left.
assumption.
apply IHxs in H0.
right.
assumption.
Qed.
Lemma closure_In: forall A (dec : x_dec A) next x y xs,
- In y (closure A dec next x xs) -> In y xs.
+ set_In y (closure A dec next x xs) -> set_In y xs.
Proof.
intros until xs.
pattern x, xs, (closure A dec next x xs).
apply closure_ind; simpl; intros.
contradiction.
rewrite <- e.
decompose [or] H.
rewrite <- H0.
assumption.
contradiction.
rewrite <- e.
decompose [or] H0.
rewrite <- H1.
assumption.
apply H in H1.
apply remove_In in H1.
assumption.
contradiction.
Qed.
Lemma closures_In: forall A (dec : x_dec A) next x xs ys,
- In x (closures A dec next xs ys) -> In x ys.
+ set_In x (closures A dec next xs ys) -> set_In x ys.
Proof.
unfold closures.
induction xs; simpl; intros.
contradiction.
apply set_union_elim in H.
elim H; intros.
apply closure_In in H0.
assumption.
apply IHxs.
assumption.
Qed.
\ No newline at end of file
diff --git a/GC_impl.v b/GC_impl.v
index 4cab133..4181048 100644
--- a/GC_impl.v
+++ b/GC_impl.v
@@ -1,45 +1,45 @@
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import GC.
+Require Import Closure.
Require Import Util.
Definition marker {A : Type} (dec : x_dec A) (m : Mem) :=
let marks :=
closuresM dec m
in
mkMem A (roots m)
(nodes m)
(frees m)
(fun x => if set_In_dec dec x marks then Marked else Unmarked)
(pointer m).
Definition sweeper {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
mkMem A (roots m)
(nodes m)
(set_union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Marked) @@ nodes m))
(fun _ => Unmarked)
(pointer m).
-Lemma closure_In: forall A (dec : x_dec A) next x xs,
- In x (Closure.closure A dec next x xs) -> In x xs.
-Proof.
-intros until xs.
-pattern x,xs,(Closure.closure A dec next x xs).
-apply Closure.closure_ind; simpl; intros; auto; try contradiction.
-
-
Theorem marker_correct: forall A (dec : x_dec A) m1 m2,
m2 = marker dec m1 -> Marker dec m1 m2.
Proof.
unfold marker, Marker.
intros.
destruct m2.
inversion H.
repeat split; auto.
unfold closuresM, marksM, Included.
simpl.
intros.
unfold marks.
apply filter_dec_In_intro.
- unfold closures in H0.
+ unfold In in H0.
+ apply closures_In in H0.
+ assumption.
+
+ destruct (set_In_dec dec x).
+ reflexivity.
+ contradiction.
+Qed.
diff --git a/OMakefile b/OMakefile
index ecc131a..16fc43a 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,19 +1,19 @@
FILES[] =
Util
Closure
GC
GC_fact
-#(* GC_impl*)
+ GC_impl
.PHONY: clean graph doc all
.DEFAULT: all
all: $(CoqProof $(FILES))
clean:
rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock
doc: $(addsuffix .v, $(FILES))
mkdir -p doc
coqdoc -d doc *.v
|
mzp/GC | 27163c67a2e2626c82e8a7a09af5e3be1aa09a34 | closures_Inã証æ | diff --git a/Closure.v b/Closure.v
index 9bbad8f..352cad6 100644
--- a/Closure.v
+++ b/Closure.v
@@ -1,71 +1,132 @@
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
Require Import Recdef.
-Section Closure.
- Variable A : Type.
- Variable dec : x_dec A.
-
- Lemma remove_dec : forall x xs,
- set_In x xs ->
- length (set_remove dec x xs) < length xs.
- Proof.
- intros.
- induction xs.
- inversion H.
-
- simpl.
- destruct (dec x a).
- apply Lt.lt_n_Sn.
-
- simpl.
- apply Lt.lt_n_S.
- apply IHxs.
- inversion H.
- rewrite H0 in n.
- assert False.
- apply n.
- reflexivity.
-
- contradiction.
-
- apply H0.
- Qed.
-
- Function closure (next : A -> option A) (x : A) (xs : set A) {measure length xs} : set A :=
- match xs with
- | nil =>
- empty_set A
- | _ =>
- if set_In_dec dec x xs then
- match next x with
- | None => empty_set A
- | Some y => closure next y (set_remove dec x xs)
- end
- else
- empty_set A
- end.
- Proof.
- intros.
+Lemma remove_dec : forall A (dec : x_dec A) x xs,
+ set_In x xs -> length (set_remove dec x xs) < length xs.
+Proof.
+intros.
+induction xs.
+ inversion H.
+
+ simpl.
+ destruct (dec x a).
+ apply Lt.lt_n_Sn.
+
simpl.
- destruct (dec x a).
- apply Lt.lt_n_Sn.
-
- simpl.
- apply Lt.lt_n_S.
- apply remove_dec.
- destruct (set_In_dec dec x (a :: l)).
- inversion s.
- rewrite H in n.
- assert False.
- apply n.
- reflexivity.
-
- contradiction.
-
- tauto.
-
- discriminate.
- Qed.
-End Closure.
+ apply Lt.lt_n_S.
+ apply IHxs.
+ inversion H.
+ rewrite H0 in n.
+ assert False.
+ apply n.
+ reflexivity.
+
+ contradiction.
+
+ apply H0.
+Qed.
+
+Function closure (A : Type) (dec : x_dec A) (next : A -> option A) (x : A) (xs : set A) {measure length xs} : set A :=
+ match xs with
+ | nil =>
+ empty_set A
+ | _ =>
+ if set_In_dec dec x xs then
+ match next x with
+ | None => x :: empty_set A
+ | Some y => x :: closure A dec next y (set_remove dec x xs)
+ end
+ else
+ empty_set A
+ end.
+Proof.
+intros.
+simpl.
+destruct (dec x a).
+ apply Lt.lt_n_Sn.
+
+ simpl.
+ apply Lt.lt_n_S.
+ apply remove_dec.
+ destruct (set_In_dec dec x (a :: l)).
+ inversion s.
+ rewrite H in n.
+ assert False.
+ apply n.
+ reflexivity.
+ contradiction.
+
+ tauto.
+
+ discriminate.
+Qed.
+
+Definition closures (A : Type) (dec : x_dec A) (next : A -> option A) (roots : set A) (nodes : set A) : set A :=
+ fold_right (set_union dec)
+ (empty_set A)
+ (map (fun x => closure A dec next x nodes) roots).
+
+
+Lemma remove_In : forall A (dec : x_dec A) x y xs,
+ set_In y (set_remove dec x xs) -> set_In y xs.
+Proof.
+induction xs; simpl; intros.
+ contradiction.
+
+ destruct (dec x a).
+ right.
+ assumption.
+
+ inversion H.
+ left.
+ assumption.
+
+ apply IHxs in H0.
+ right.
+ assumption.
+Qed.
+
+Lemma closure_In: forall A (dec : x_dec A) next x y xs,
+ In y (closure A dec next x xs) -> In y xs.
+Proof.
+intros until xs.
+pattern x, xs, (closure A dec next x xs).
+apply closure_ind; simpl; intros.
+ contradiction.
+
+ rewrite <- e.
+ decompose [or] H.
+ rewrite <- H0.
+ assumption.
+
+ contradiction.
+
+ rewrite <- e.
+ decompose [or] H0.
+ rewrite <- H1.
+ assumption.
+
+ apply H in H1.
+ apply remove_In in H1.
+ assumption.
+
+ contradiction.
+Qed.
+
+Lemma closures_In: forall A (dec : x_dec A) next x xs ys,
+ In x (closures A dec next xs ys) -> In x ys.
+Proof.
+unfold closures.
+induction xs; simpl; intros.
+ contradiction.
+
+ apply set_union_elim in H.
+ elim H; intros.
+ apply closure_In in H0.
+ assumption.
+
+ apply IHxs.
+ assumption.
+Qed.
\ No newline at end of file
diff --git a/GC.v b/GC.v
index 15a385e..0cc55b6 100644
--- a/GC.v
+++ b/GC.v
@@ -1,80 +1,75 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
Require Import Closure.
(** * operations of set *)
Definition In {A : Type} (elem : A) (sets : set A) :=
set_In elem sets.
Definition Included {A : Type} (B C : set A) : Prop :=
forall x, In x B -> In x C.
Definition Union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
set_union dec B C.
(** * Memory *)
Inductive mark :=
| Marked : mark
| Unmarked : mark.
Definition mark_dec : forall (m1 m2 : mark), { m1 = m2} + { m1 <> m2}.
Proof.
decide equality.
Qed.
Record Mem {A : Type} := mkMem {
roots : set A; (** root objects *)
nodes : set A; (** all objects in memory *)
frees : set A; (** free list *)
marker : A -> mark; (** get mark of the object *)
pointer : A -> option A (** get next object of the object *)
}.
Lemma destruct_mem : forall A m,
m = mkMem A (roots m) (nodes m) (frees m) (marker m) (pointer m).
Proof.
intros.
destruct m.
simpl.
reflexivity.
Qed.
(** * GC *)
(** ** closure *)
-Definition closures (A : Type) (dec : x_dec A) (next : A -> option A) (roots : set A) (nodes : set A) : set A :=
- fold_left (set_union dec)
- (map (fun x => closure A dec next x nodes) roots)
- (empty_set A).
-
Definition closuresM {A : Type} (dec : x_dec A) (m : Mem) :=
closures A dec (pointer m) (roots m) (nodes m).
(** ** Marker utility *)
Definition marks (A : Type) (marker : A -> mark) (ma : mark) (xs : set A) : set A :=
filter_dec (fun x => mark_dec (marker x) ma) xs.
Definition marksM {A : Type} (ma : mark) (m : Mem) :=
marks A (marker m) ma (nodes m).
(** ** main GC *)
(** marker *)
Definition Marker {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
frees m1 = frees m2 /\
pointer m1 = pointer m2 /\
Included (closuresM dec m2) (marksM Marked m2).
(** sweeper *)
Definition Sweeper {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
pointer m1 = pointer m2 /\
frees m2 = Union dec (frees m1) (marksM Unmarked m1) /\
forall (n : A), In n (nodes m2) -> marker m2 n = Unmarked.
(** mark & sweep GC *)
Definition GC {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) := exists m : Mem,
Marker dec m1 m /\ Sweeper dec m m2.
diff --git a/GC_fact.v b/GC_fact.v
index 7513447..a9b30c1 100644
--- a/GC_fact.v
+++ b/GC_fact.v
@@ -1,150 +1,150 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
Require Import GC.
(** Invariant *)
Definition Invariant {A : Type} (m : Mem) : Prop :=
Included (roots m) (nodes m) /\
Included (frees m) (nodes m) /\
forall (x y :A), In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
Lemma marker_invariant : forall A dec (m1 m2 : Mem (A:=A)),
Marker dec m1 m2 -> Invariant m1 -> Invariant m2.
Proof.
unfold Marker, Invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <-H1, <-H2, <-H3, <-H4.
repeat split; auto.
Qed.
Lemma Marks_include : forall A xs marker m,
Included (marks A marker m xs) xs.
Proof.
unfold Included, marks, In, set_In.
intros.
-apply filter_dec_In in H.
+apply filter_dec_In_elim in H.
decompose [and] H.
tauto.
Qed.
Lemma sweeper_invariant: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Sweeper dec m1 m2 -> Invariant m1 -> Invariant m2.
Proof.
unfold Sweeper, Invariant, Union.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <- H1, <- H2, <- H3, H4.
repeat split; auto.
unfold Included.
intros.
unfold In in H7.
apply set_union_elim in H7.
decompose [or] H7.
apply H8 in H10.
tauto.
apply (Marks_include _ _ (marker m1) Unmarked _).
tauto.
Qed.
Theorem gc_invariant : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Invariant m1 -> GC dec m1 m2 -> Invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_invariant in H2; auto.
apply sweeper_invariant in H3; auto.
Qed.
(** safety *)
Definition Disjoint {A : Type} (xs ys : set A) := forall x,
(set_In x xs -> ~ set_In x ys) /\ (set_In x ys -> ~ set_In x xs).
Definition Safety {A : Type} (dec : x_dec A) (m : Mem) : Prop :=
Disjoint (frees m) (closuresM dec m).
Definition MarksAll {A : Type} (dec : x_dec A) (m : Mem) : Prop :=
Disjoint (marksM Unmarked m) (closuresM dec m).
Lemma sweeper_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety dec m1 -> MarksAll dec m1 -> Sweeper dec m1 m2 -> Safety dec m2.
Proof.
unfold Safety, MarksAll, Sweeper, closuresM, Disjoint, Union, In.
intros.
decompose [and] (H x).
decompose [and] (H0 x).
decompose [and] H1.
rewrite <- H6, <- H7, <- H8, H9.
split; intros.
apply set_union_elim in H10.
decompose [or] H10.
apply H2 in H12.
tauto.
apply H4 in H12.
tauto.
intro.
apply set_union_elim in H12.
decompose [or] H12.
apply H2 in H13.
contradiction.
apply H4 in H13.
contradiction.
Qed.
Lemma marks_In : forall A m ma (x : A),
In x (marksM ma m) -> marker m x = ma.
Proof.
unfold In, marksM, marks.
intros.
-apply filter_dec_In in H.
+apply filter_dec_In_elim in H.
decompose [and] H.
assumption.
Qed.
Lemma marker_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety dec m1 -> Marker dec m1 m2 -> Safety dec m2 /\ MarksAll dec m2.
Proof.
unfold Safety, MarksAll, Marker, closuresM, Disjoint, Union, In, Included.
intros.
decompose [and] H0.
rewrite <- H1, <- H2,<- H3, <- H4.
rewrite <- H1, <- H3, <-H4 in H6.
repeat split; intros; decompose [and] (H x); intro.
apply H8 in H9.
contradiction.
apply H7 in H9.
contradiction.
apply (H6 x) in H9.
apply marks_In in H5.
apply marks_In in H9.
rewrite H9 in H5.
discriminate.
apply H6 in H5.
apply marks_In in H5.
apply marks_In in H9.
rewrite H9 in H5.
discriminate.
Qed.
Theorem gc_safety: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety dec m1 -> GC dec m1 m2 -> Safety dec m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_safety in H2; auto.
decompose [and] H2.
apply sweeper_safety in H3; auto.
Qed.
diff --git a/GC_impl.v b/GC_impl.v
index 327a120..4cab133 100644
--- a/GC_impl.v
+++ b/GC_impl.v
@@ -1,38 +1,45 @@
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import GC.
Require Import Util.
Definition marker {A : Type} (dec : x_dec A) (m : Mem) :=
let marks :=
closuresM dec m
in
mkMem A (roots m)
(nodes m)
(frees m)
(fun x => if set_In_dec dec x marks then Marked else Unmarked)
(pointer m).
Definition sweeper {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
mkMem A (roots m)
(nodes m)
(set_union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Marked) @@ nodes m))
(fun _ => Unmarked)
(pointer m).
+Lemma closure_In: forall A (dec : x_dec A) next x xs,
+ In x (Closure.closure A dec next x xs) -> In x xs.
+Proof.
+intros until xs.
+pattern x,xs,(Closure.closure A dec next x xs).
+apply Closure.closure_ind; simpl; intros; auto; try contradiction.
+
+
Theorem marker_correct: forall A (dec : x_dec A) m1 m2,
m2 = marker dec m1 -> Marker dec m1 m2.
Proof.
unfold marker, Marker.
intros.
destruct m2.
inversion H.
repeat split; auto.
unfold closuresM, marksM, Included.
simpl.
intros.
unfold marks.
-induction (GC.nodes m1); simpl.
+apply filter_dec_In_intro.
unfold closures in H0.
- simpl in H0.
diff --git a/OMakefile b/OMakefile
index 16fc43a..ecc131a 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,19 +1,19 @@
FILES[] =
Util
Closure
GC
GC_fact
- GC_impl
+#(* GC_impl*)
.PHONY: clean graph doc all
.DEFAULT: all
all: $(CoqProof $(FILES))
clean:
rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock
doc: $(addsuffix .v, $(FILES))
mkdir -p doc
coqdoc -d doc *.v
diff --git a/Util.v b/Util.v
index a0dc659..9dde976 100644
--- a/Util.v
+++ b/Util.v
@@ -1,40 +1,64 @@
Require Import List.
Require Import Sumbool.
Definition atat {A B:Type} (f: A -> B) x := f x.
Infix "@@" := atat (at level 60).
Definition doll {A B C: Type} (g: B -> C) (f: A -> B) (x: A) := g (f x).
Infix "$" := doll (at level 60).
Definition x_dec A :=
forall x y : A, {x = y} + {x <> y}.
-Fixpoint filter_dec {A : Type} {P Q: A -> Prop} (dec : forall x,{P x} + {Q x}) (l : list A) : list A :=
+Fixpoint filter_dec {A : Type} {P : A -> Prop} (dec : forall x,{P x} + {~ P x}) (l : list A) : list A :=
match l with
| nil => nil
| x :: xs =>
if dec x then
x::(filter_dec dec xs)
else
filter_dec dec xs
end.
-Lemma filter_dec_In : forall {A: Type} {P Q: A -> Prop} (f : forall x, {P x} + {Q x}) x l,
+Lemma filter_dec_In_elim : forall {A: Type} {P : A -> Prop} (f : forall x, {P x} + {~ P x}) x l,
In x (filter_dec f l) -> In x l /\ P x.
Proof.
-intros A P Q f.
+intros A P f.
induction l; simpl.
intro H; elim H.
case (f a); simpl in |- *.
intros H _H; elim _H; intros.
split; [ left | rewrite <- H0 in |- * ]; assumption.
elim (IHl H0); intros.
split; [ right | idtac ]; assumption.
intros _ H; elim (IHl H); intros.
split; [ right | idtac ]; assumption.
Qed.
+Lemma filter_dec_In_intro : forall {A: Type} {P: A -> Prop} (f : forall x, {P x} + {~ P x}) x l,
+ In x l -> P x -> In x (filter_dec f l).
+Proof.
+intros A P f.
+induction l; simpl.
+ intros H.
+ elim H.
+
+ destruct (f a).
+ intro H; elim H; intros; simpl.
+ left.
+ rewrite H0.
+ reflexivity.
+
+ right.
+ apply IHl; auto.
+
+ intros H.
+ elim H; intros.
+ rewrite H0 in n.
+ contradiction.
+
+ apply IHl; auto.
+Qed.
\ No newline at end of file
|
mzp/GC | 32025071821c90f7c81b0697f8c62af66d950ce7 | markerã®è¨¼æãããããã | diff --git a/GC_impl.v b/GC_impl.v
index 7090fcf..327a120 100644
--- a/GC_impl.v
+++ b/GC_impl.v
@@ -1,32 +1,38 @@
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import GC.
Require Import Util.
Definition marker {A : Type} (dec : x_dec A) (m : Mem) :=
let marks :=
closuresM dec m
in
mkMem A (roots m)
(nodes m)
(frees m)
(fun x => if set_In_dec dec x marks then Marked else Unmarked)
(pointer m).
Definition sweeper {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
mkMem A (roots m)
(nodes m)
(set_union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Marked) @@ nodes m))
(fun _ => Unmarked)
(pointer m).
Theorem marker_correct: forall A (dec : x_dec A) m1 m2,
- Marker dec m1 m2 <-> m2 = marker dec m1.
+ m2 = marker dec m1 -> Marker dec m1 m2.
Proof.
-unfold Marker, marker.
-split; intros.
- decompose [and] H.
- rewrite (destruct_mem _ m2).
- rewrite H0,H2,H1,H3.
- unfold Included in H5.
+unfold marker, Marker.
+intros.
+destruct m2.
+inversion H.
+repeat split; auto.
+unfold closuresM, marksM, Included.
+simpl.
+intros.
+unfold marks.
+induction (GC.nodes m1); simpl.
+ unfold closures in H0.
+ simpl in H0.
|
mzp/GC | 5cf2f89a7fbdc50fc4f97b5da5c149e348610671 | marker/sweeperãå®è£
ãã | diff --git a/GC.v b/GC.v
index 4d315a8..15a385e 100644
--- a/GC.v
+++ b/GC.v
@@ -1,70 +1,80 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
Require Import Closure.
(** * operations of set *)
Definition In {A : Type} (elem : A) (sets : set A) :=
set_In elem sets.
Definition Included {A : Type} (B C : set A) : Prop :=
forall x, In x B -> In x C.
Definition Union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
set_union dec B C.
(** * Memory *)
Inductive mark :=
| Marked : mark
| Unmarked : mark.
Definition mark_dec : forall (m1 m2 : mark), { m1 = m2} + { m1 <> m2}.
Proof.
decide equality.
Qed.
Record Mem {A : Type} := mkMem {
roots : set A; (** root objects *)
nodes : set A; (** all objects in memory *)
frees : set A; (** free list *)
marker : A -> mark; (** get mark of the object *)
pointer : A -> option A (** get next object of the object *)
}.
+Lemma destruct_mem : forall A m,
+ m = mkMem A (roots m) (nodes m) (frees m) (marker m) (pointer m).
+Proof.
+intros.
+destruct m.
+simpl.
+reflexivity.
+Qed.
+
+
(** * GC *)
(** ** closure *)
Definition closures (A : Type) (dec : x_dec A) (next : A -> option A) (roots : set A) (nodes : set A) : set A :=
fold_left (set_union dec)
(map (fun x => closure A dec next x nodes) roots)
(empty_set A).
Definition closuresM {A : Type} (dec : x_dec A) (m : Mem) :=
closures A dec (pointer m) (roots m) (nodes m).
(** ** Marker utility *)
Definition marks (A : Type) (marker : A -> mark) (ma : mark) (xs : set A) : set A :=
filter_dec (fun x => mark_dec (marker x) ma) xs.
Definition marksM {A : Type} (ma : mark) (m : Mem) :=
marks A (marker m) ma (nodes m).
(** ** main GC *)
(** marker *)
Definition Marker {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
frees m1 = frees m2 /\
pointer m1 = pointer m2 /\
Included (closuresM dec m2) (marksM Marked m2).
(** sweeper *)
Definition Sweeper {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
pointer m1 = pointer m2 /\
frees m2 = Union dec (frees m1) (marksM Unmarked m1) /\
forall (n : A), In n (nodes m2) -> marker m2 n = Unmarked.
(** mark & sweep GC *)
Definition GC {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) := exists m : Mem,
Marker dec m1 m /\ Sweeper dec m m2.
diff --git a/GC_impl.v b/GC_impl.v
index 930afc0..7090fcf 100644
--- a/GC_impl.v
+++ b/GC_impl.v
@@ -1,71 +1,32 @@
-Require Import GC.
Require Import Lists.ListSet.
Require Import Lists.List.
+Require Import GC.
Require Import Util.
-Require Import Recdef.
-Variable A : Type.
-Variable dec : x_dec A.
-
-Lemma remove_dec : forall x xs,
- set_In x xs ->
- length (set_remove dec x xs) < length xs.
+Definition marker {A : Type} (dec : x_dec A) (m : Mem) :=
+ let marks :=
+ closuresM dec m
+ in
+ mkMem A (roots m)
+ (nodes m)
+ (frees m)
+ (fun x => if set_In_dec dec x marks then Marked else Unmarked)
+ (pointer m).
+
+Definition sweeper {A : Type} (dec : x_dec A) (m : Mem) : Mem :=
+ mkMem A (roots m)
+ (nodes m)
+ (set_union dec (frees m) (filter_dec (fun n => mark_dec (GC.marker m n) Marked) @@ nodes m))
+ (fun _ => Unmarked)
+ (pointer m).
+
+Theorem marker_correct: forall A (dec : x_dec A) m1 m2,
+ Marker dec m1 m2 <-> m2 = marker dec m1.
Proof.
-intros.
-induction xs.
- inversion H.
-
- simpl.
- destruct (dec x a).
- apply Lt.lt_n_Sn.
-
- simpl.
- apply Lt.lt_n_S.
- apply IHxs.
- inversion H.
- rewrite H0 in n.
- assert False.
- apply n.
- reflexivity.
-
- contradiction.
-
- apply H0.
-Qed.
-
-Function closure (next : A -> option A) (x : A) (xs : set A) {measure length xs} : set A :=
- match xs with
- | nil =>
- empty_set A
- | _ =>
- if set_In_dec dec x xs then
- match next x with
- | None => empty_set A
- | Some y => closure next y (set_remove dec x xs)
- end
- else
- empty_set A
- end.
-Proof.
-intros.
-simpl.
-destruct (dec x a).
- apply Lt.lt_n_Sn.
-
- simpl.
- apply Lt.lt_n_S.
- apply remove_dec.
- destruct (set_In_dec dec x (a :: l)).
- inversion s.
- rewrite H in n.
- assert False.
- apply n.
- reflexivity.
-
- contradiction.
-
- tauto.
-
- discriminate.
-Qed.
+unfold Marker, marker.
+split; intros.
+ decompose [and] H.
+ rewrite (destruct_mem _ m2).
+ rewrite H0,H2,H1,H3.
+ unfold Included in H5.
diff --git a/OMakefile b/OMakefile
index bf17f0a..16fc43a 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,18 +1,19 @@
FILES[] =
Util
Closure
GC
GC_fact
+ GC_impl
.PHONY: clean graph doc all
.DEFAULT: all
all: $(CoqProof $(FILES))
clean:
rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock
doc: $(addsuffix .v, $(FILES))
mkdir -p doc
coqdoc -d doc *.v
diff --git a/Util.v b/Util.v
index 3a41c83..a0dc659 100644
--- a/Util.v
+++ b/Util.v
@@ -1,32 +1,40 @@
Require Import List.
+Require Import Sumbool.
+
+Definition atat {A B:Type} (f: A -> B) x := f x.
+Infix "@@" := atat (at level 60).
+
+Definition doll {A B C: Type} (g: B -> C) (f: A -> B) (x: A) := g (f x).
+Infix "$" := doll (at level 60).
+
Definition x_dec A :=
forall x y : A, {x = y} + {x <> y}.
Fixpoint filter_dec {A : Type} {P Q: A -> Prop} (dec : forall x,{P x} + {Q x}) (l : list A) : list A :=
match l with
| nil => nil
| x :: xs =>
if dec x then
x::(filter_dec dec xs)
else
filter_dec dec xs
end.
Lemma filter_dec_In : forall {A: Type} {P Q: A -> Prop} (f : forall x, {P x} + {Q x}) x l,
In x (filter_dec f l) -> In x l /\ P x.
Proof.
intros A P Q f.
induction l; simpl.
intro H; elim H.
case (f a); simpl in |- *.
intros H _H; elim _H; intros.
split; [ left | rewrite <- H0 in |- * ]; assumption.
elim (IHl H0); intros.
split; [ right | idtac ]; assumption.
intros _ H; elim (IHl H); intros.
split; [ right | idtac ]; assumption.
Qed.
|
mzp/GC | ba009afbdcca8989479a5ee24ec18b1834533554 | ã³ã¼ããæ´çãã | diff --git a/GC_fact.v b/GC_fact.v
index b05cf6c..7513447 100644
--- a/GC_fact.v
+++ b/GC_fact.v
@@ -1,152 +1,150 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
Require Import GC.
-(** invariant *)
-Definition invariant {A : Type} (m : Mem) : Prop :=
+(** Invariant *)
+Definition Invariant {A : Type} (m : Mem) : Prop :=
Included (roots m) (nodes m) /\
Included (frees m) (nodes m) /\
forall (x y :A), In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
-
Lemma marker_invariant : forall A dec (m1 m2 : Mem (A:=A)),
- Marker dec m1 m2 -> invariant m1 -> invariant m2.
+ Marker dec m1 m2 -> Invariant m1 -> Invariant m2.
Proof.
-unfold Marker, invariant.
+unfold Marker, Invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <-H1, <-H2, <-H3, <-H4.
repeat split; auto.
Qed.
Lemma Marks_include : forall A xs marker m,
Included (marks A marker m xs) xs.
Proof.
unfold Included, marks, In, set_In.
intros.
apply filter_dec_In in H.
decompose [and] H.
tauto.
Qed.
Lemma sweeper_invariant: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
- Sweeper dec m1 m2 -> invariant m1 -> invariant m2.
+ Sweeper dec m1 m2 -> Invariant m1 -> Invariant m2.
Proof.
-unfold Sweeper, invariant, Union.
+unfold Sweeper, Invariant, Union.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <- H1, <- H2, <- H3, H4.
repeat split; auto.
unfold Included.
intros.
unfold In in H7.
apply set_union_elim in H7.
decompose [or] H7.
apply H8 in H10.
tauto.
apply (Marks_include _ _ (marker m1) Unmarked _).
tauto.
Qed.
Theorem gc_invariant : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
- invariant m1 -> GC dec m1 m2 -> invariant m2.
+ Invariant m1 -> GC dec m1 m2 -> Invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_invariant in H2; auto.
apply sweeper_invariant in H3; auto.
Qed.
(** safety *)
Definition Disjoint {A : Type} (xs ys : set A) := forall x,
- (set_In x xs -> ~ set_In x ys) /\
- (set_In x ys -> ~ set_In x xs).
+ (set_In x xs -> ~ set_In x ys) /\ (set_In x ys -> ~ set_In x xs).
Definition Safety {A : Type} (dec : x_dec A) (m : Mem) : Prop :=
Disjoint (frees m) (closuresM dec m).
Definition MarksAll {A : Type} (dec : x_dec A) (m : Mem) : Prop :=
Disjoint (marksM Unmarked m) (closuresM dec m).
Lemma sweeper_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety dec m1 -> MarksAll dec m1 -> Sweeper dec m1 m2 -> Safety dec m2.
Proof.
unfold Safety, MarksAll, Sweeper, closuresM, Disjoint, Union, In.
intros.
decompose [and] (H x).
decompose [and] (H0 x).
decompose [and] H1.
rewrite <- H6, <- H7, <- H8, H9.
split; intros.
apply set_union_elim in H10.
decompose [or] H10.
apply H2 in H12.
tauto.
apply H4 in H12.
tauto.
intro.
apply set_union_elim in H12.
decompose [or] H12.
apply H2 in H13.
contradiction.
apply H4 in H13.
contradiction.
Qed.
Lemma marks_In : forall A m ma (x : A),
In x (marksM ma m) -> marker m x = ma.
Proof.
unfold In, marksM, marks.
intros.
apply filter_dec_In in H.
decompose [and] H.
assumption.
Qed.
Lemma marker_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety dec m1 -> Marker dec m1 m2 -> Safety dec m2 /\ MarksAll dec m2.
Proof.
unfold Safety, MarksAll, Marker, closuresM, Disjoint, Union, In, Included.
intros.
decompose [and] H0.
rewrite <- H1, <- H2,<- H3, <- H4.
rewrite <- H1, <- H3, <-H4 in H6.
repeat split; intros; decompose [and] (H x); intro.
apply H8 in H9.
contradiction.
apply H7 in H9.
contradiction.
apply (H6 x) in H9.
apply marks_In in H5.
apply marks_In in H9.
rewrite H9 in H5.
discriminate.
apply H6 in H5.
apply marks_In in H5.
apply marks_In in H9.
rewrite H9 in H5.
discriminate.
Qed.
Theorem gc_safety: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety dec m1 -> GC dec m1 m2 -> Safety dec m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_safety in H2; auto.
decompose [and] H2.
apply sweeper_safety in H3; auto.
Qed.
|
mzp/GC | 8ad0142a284a04c000f51eb30a63fccabc9cf016 | closureã使ã£ã¦è¨¼æãæ¸ãç´ãã | diff --git a/Closure.v b/Closure.v
new file mode 100644
index 0000000..9bbad8f
--- /dev/null
+++ b/Closure.v
@@ -0,0 +1,71 @@
+Require Import Lists.ListSet.
+Require Import Lists.List.
+Require Import Util.
+Require Import Recdef.
+
+Section Closure.
+ Variable A : Type.
+ Variable dec : x_dec A.
+
+ Lemma remove_dec : forall x xs,
+ set_In x xs ->
+ length (set_remove dec x xs) < length xs.
+ Proof.
+ intros.
+ induction xs.
+ inversion H.
+
+ simpl.
+ destruct (dec x a).
+ apply Lt.lt_n_Sn.
+
+ simpl.
+ apply Lt.lt_n_S.
+ apply IHxs.
+ inversion H.
+ rewrite H0 in n.
+ assert False.
+ apply n.
+ reflexivity.
+
+ contradiction.
+
+ apply H0.
+ Qed.
+
+ Function closure (next : A -> option A) (x : A) (xs : set A) {measure length xs} : set A :=
+ match xs with
+ | nil =>
+ empty_set A
+ | _ =>
+ if set_In_dec dec x xs then
+ match next x with
+ | None => empty_set A
+ | Some y => closure next y (set_remove dec x xs)
+ end
+ else
+ empty_set A
+ end.
+ Proof.
+ intros.
+ simpl.
+ destruct (dec x a).
+ apply Lt.lt_n_Sn.
+
+ simpl.
+ apply Lt.lt_n_S.
+ apply remove_dec.
+ destruct (set_In_dec dec x (a :: l)).
+ inversion s.
+ rewrite H in n.
+ assert False.
+ apply n.
+ reflexivity.
+
+ contradiction.
+
+ tauto.
+
+ discriminate.
+ Qed.
+End Closure.
diff --git a/GC.v b/GC.v
index 259268d..4d315a8 100644
--- a/GC.v
+++ b/GC.v
@@ -1,75 +1,70 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
+Require Import Closure.
(** * operations of set *)
Definition In {A : Type} (elem : A) (sets : set A) :=
set_In elem sets.
Definition Included {A : Type} (B C : set A) : Prop :=
forall x, In x B -> In x C.
Definition Union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
set_union dec B C.
(** * Memory *)
Inductive mark :=
| Marked : mark
| Unmarked : mark.
Definition mark_dec : forall (m1 m2 : mark), { m1 = m2} + { m1 <> m2}.
Proof.
decide equality.
Qed.
Record Mem {A : Type} := mkMem {
roots : set A; (** root objects *)
nodes : set A; (** all objects in memory *)
frees : set A; (** free list *)
marker : A -> mark; (** get mark of the object *)
pointer : A -> option A (** get next object of the object *)
}.
(** * GC *)
(** ** closure *)
-(** [Closure A next x] means a set: {x, next x, next (next x), ... }. *)
-Inductive Connect (A : Type) (next : A -> option A) (root : A) : A -> Prop:=
- | CRoot :
- Connect A next root root
- | CTrans : forall x y,
- Some y = next x -> Connect A next y x -> Connect A next root x.
+Definition closures (A : Type) (dec : x_dec A) (next : A -> option A) (roots : set A) (nodes : set A) : set A :=
+ fold_left (set_union dec)
+ (map (fun x => closure A dec next x nodes) roots)
+ (empty_set A).
-Inductive ConnectS (A : Type) (next : A -> option A) (roots : set A) : A -> Prop :=
- | ConnectSet_intro : forall n m,
- In m roots -> Connect A next m n -> ConnectS A next roots n.
-
-Definition ConnectM {A : Type} (m : Mem) :=
- ConnectS A (pointer m) (roots m).
+Definition closuresM {A : Type} (dec : x_dec A) (m : Mem) :=
+ closures A dec (pointer m) (roots m) (nodes m).
(** ** Marker utility *)
Definition marks (A : Type) (marker : A -> mark) (ma : mark) (xs : set A) : set A :=
- filter (fun x => if mark_dec (marker x) ma then true else false) xs.
+ filter_dec (fun x => mark_dec (marker x) ma) xs.
Definition marksM {A : Type} (ma : mark) (m : Mem) :=
marks A (marker m) ma (nodes m).
(** ** main GC *)
(** marker *)
-Definition Marker {A : Type} (m1 m2 : Mem (A:=A)) : Prop :=
+Definition Marker {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
frees m1 = frees m2 /\
pointer m1 = pointer m2 /\
- forall x, ConnectM m2 x -> marker m2 x = Marked.
+ Included (closuresM dec m2) (marksM Marked m2).
(** sweeper *)
Definition Sweeper {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
pointer m1 = pointer m2 /\
frees m2 = Union dec (frees m1) (marksM Unmarked m1) /\
forall (n : A), In n (nodes m2) -> marker m2 n = Unmarked.
(** mark & sweep GC *)
Definition GC {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) := exists m : Mem,
- Marker m1 m /\ Sweeper dec m m2.
+ Marker dec m1 m /\ Sweeper dec m m2.
diff --git a/GC_fact.v b/GC_fact.v
index b16431d..b05cf6c 100644
--- a/GC_fact.v
+++ b/GC_fact.v
@@ -1,149 +1,152 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
Require Import Util.
Require Import GC.
(** invariant *)
Definition invariant {A : Type} (m : Mem) : Prop :=
Included (roots m) (nodes m) /\
Included (frees m) (nodes m) /\
forall (x y :A), In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
-Lemma marker_invariant : forall A (m1 m2 : Mem (A:=A)),
- Marker m1 m2 -> invariant m1 -> invariant m2.
+
+Lemma marker_invariant : forall A dec (m1 m2 : Mem (A:=A)),
+ Marker dec m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Marker, invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <-H1, <-H2, <-H3, <-H4.
repeat split; auto.
Qed.
Lemma Marks_include : forall A xs marker m,
Included (marks A marker m xs) xs.
Proof.
unfold Included, marks, In, set_In.
intros.
-apply filter_In in H.
+apply filter_dec_In in H.
decompose [and] H.
tauto.
Qed.
Lemma sweeper_invariant: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Sweeper dec m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Sweeper, invariant, Union.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <- H1, <- H2, <- H3, H4.
repeat split; auto.
unfold Included.
intros.
unfold In in H7.
apply set_union_elim in H7.
decompose [or] H7.
apply H8 in H10.
tauto.
apply (Marks_include _ _ (marker m1) Unmarked _).
tauto.
Qed.
Theorem gc_invariant : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
invariant m1 -> GC dec m1 m2 -> invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_invariant in H2; auto.
apply sweeper_invariant in H3; auto.
Qed.
(** safety *)
-Definition disjoint (P Q : Prop) :=
- (P -> ~ Q) /\ (Q -> ~ P).
+Definition Disjoint {A : Type} (xs ys : set A) := forall x,
+ (set_In x xs -> ~ set_In x ys) /\
+ (set_In x ys -> ~ set_In x xs).
-Definition Safety {A : Type} (m : Mem) : Prop := forall x : A,
- disjoint (In x (frees m)) (ConnectM m x).
+Definition Safety {A : Type} (dec : x_dec A) (m : Mem) : Prop :=
+ Disjoint (frees m) (closuresM dec m).
-Definition MarksAll {A : Type} (m : Mem) : Prop := forall x : A,
- disjoint (In x (marksM Unmarked m)) (ConnectM m x).
+Definition MarksAll {A : Type} (dec : x_dec A) (m : Mem) : Prop :=
+ Disjoint (marksM Unmarked m) (closuresM dec m).
Lemma sweeper_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
- Safety m1 -> MarksAll m1 -> Sweeper dec m1 m2 -> Safety m2.
+ Safety dec m1 -> MarksAll dec m1 -> Sweeper dec m1 m2 -> Safety dec m2.
Proof.
-unfold Safety, MarksAll, Sweeper, ConnectM, disjoint, Union, In.
+unfold Safety, MarksAll, Sweeper, closuresM, Disjoint, Union, In.
intros.
decompose [and] (H x).
decompose [and] (H0 x).
decompose [and] H1.
-rewrite <- H6, <- H7, H9.
+rewrite <- H6, <- H7, <- H8, H9.
split; intros.
apply set_union_elim in H10.
decompose [or] H10.
apply H2 in H12.
tauto.
apply H4 in H12.
tauto.
intro.
apply set_union_elim in H12.
decompose [or] H12.
apply H2 in H13.
contradiction.
apply H4 in H13.
contradiction.
Qed.
-Lemma marker_safety : forall A (m1 m2 : Mem (A:=A)),
- Safety m1 -> Marker m1 m2 -> Safety m2 /\ MarksAll m2.
+Lemma marks_In : forall A m ma (x : A),
+ In x (marksM ma m) -> marker m x = ma.
Proof.
-unfold Safety, MarksAll, Marker, ConnectM, disjoint, Union, In.
+unfold In, marksM, marks.
+intros.
+apply filter_dec_In in H.
+decompose [and] H.
+assumption.
+Qed.
+
+Lemma marker_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
+ Safety dec m1 -> Marker dec m1 m2 -> Safety dec m2 /\ MarksAll dec m2.
+Proof.
+unfold Safety, MarksAll, Marker, closuresM, Disjoint, Union, In, Included.
intros.
decompose [and] H0.
-rewrite <- H1, <- H2, <- H4.
-rewrite <- H1, <-H4 in H6.
+rewrite <- H1, <- H2,<- H3, <- H4.
+rewrite <- H1, <- H3, <-H4 in H6.
repeat split; intros; decompose [and] (H x); intro.
apply H8 in H9.
contradiction.
apply H7 in H9.
contradiction.
- generalize H9; intro.
apply (H6 x) in H9.
- unfold marksM, marks in H5.
- apply filter_In in H5.
- decompose [and] H5.
- destruct (mark_dec (marker m2 x)).
- rewrite H9 in e.
- discriminate.
-
- discriminate.
+ apply marks_In in H5.
+ apply marks_In in H9.
+ rewrite H9 in H5.
+ discriminate.
apply H6 in H5.
- unfold marksM, marks in H9.
- apply filter_In in H9.
- decompose [and] H9.
- destruct (mark_dec (marker m2 x)).
- rewrite H5 in e.
- discriminate.
-
- discriminate.
+ apply marks_In in H5.
+ apply marks_In in H9.
+ rewrite H9 in H5.
+ discriminate.
Qed.
Theorem gc_safety: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
- Safety m1 -> GC dec m1 m2 -> Safety m2.
+ Safety dec m1 -> GC dec m1 m2 -> Safety dec m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_safety in H2; auto.
decompose [and] H2.
apply sweeper_safety in H3; auto.
Qed.
diff --git a/OMakefile b/OMakefile
index 45e4465..bf17f0a 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,17 +1,18 @@
FILES[] =
Util
+ Closure
GC
GC_fact
.PHONY: clean graph doc all
.DEFAULT: all
all: $(CoqProof $(FILES))
clean:
rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock
doc: $(addsuffix .v, $(FILES))
mkdir -p doc
coqdoc -d doc *.v
diff --git a/Util.v b/Util.v
index a2dec9a..3a41c83 100644
--- a/Util.v
+++ b/Util.v
@@ -1,2 +1,32 @@
+Require Import List.
Definition x_dec A :=
- forall x y : A, {x = y} + {x <> y}.
\ No newline at end of file
+ forall x y : A, {x = y} + {x <> y}.
+
+Fixpoint filter_dec {A : Type} {P Q: A -> Prop} (dec : forall x,{P x} + {Q x}) (l : list A) : list A :=
+ match l with
+ | nil => nil
+ | x :: xs =>
+ if dec x then
+ x::(filter_dec dec xs)
+ else
+ filter_dec dec xs
+ end.
+
+Lemma filter_dec_In : forall {A: Type} {P Q: A -> Prop} (f : forall x, {P x} + {Q x}) x l,
+ In x (filter_dec f l) -> In x l /\ P x.
+Proof.
+intros A P Q f.
+induction l; simpl.
+ intro H; elim H.
+
+ case (f a); simpl in |- *.
+ intros H _H; elim _H; intros.
+ split; [ left | rewrite <- H0 in |- * ]; assumption.
+
+ elim (IHl H0); intros.
+ split; [ right | idtac ]; assumption.
+
+ intros _ H; elim (IHl H); intros.
+ split; [ right | idtac ]; assumption.
+Qed.
+
|
mzp/GC | 12ab96864bd7c34f2b1012d7935bd0ac867c5d00 | closureãå®è£
ãã¦ã¿ã | diff --git a/GC_impl.v b/GC_impl.v
new file mode 100644
index 0000000..930afc0
--- /dev/null
+++ b/GC_impl.v
@@ -0,0 +1,71 @@
+Require Import GC.
+Require Import Lists.ListSet.
+Require Import Lists.List.
+Require Import Util.
+Require Import Recdef.
+
+Variable A : Type.
+Variable dec : x_dec A.
+
+Lemma remove_dec : forall x xs,
+ set_In x xs ->
+ length (set_remove dec x xs) < length xs.
+Proof.
+intros.
+induction xs.
+ inversion H.
+
+ simpl.
+ destruct (dec x a).
+ apply Lt.lt_n_Sn.
+
+ simpl.
+ apply Lt.lt_n_S.
+ apply IHxs.
+ inversion H.
+ rewrite H0 in n.
+ assert False.
+ apply n.
+ reflexivity.
+
+ contradiction.
+
+ apply H0.
+Qed.
+
+Function closure (next : A -> option A) (x : A) (xs : set A) {measure length xs} : set A :=
+ match xs with
+ | nil =>
+ empty_set A
+ | _ =>
+ if set_In_dec dec x xs then
+ match next x with
+ | None => empty_set A
+ | Some y => closure next y (set_remove dec x xs)
+ end
+ else
+ empty_set A
+ end.
+Proof.
+intros.
+simpl.
+destruct (dec x a).
+ apply Lt.lt_n_Sn.
+
+ simpl.
+ apply Lt.lt_n_S.
+ apply remove_dec.
+ destruct (set_In_dec dec x (a :: l)).
+ inversion s.
+ rewrite H in n.
+ assert False.
+ apply n.
+ reflexivity.
+
+ contradiction.
+
+ tauto.
+
+ discriminate.
+Qed.
+
|
mzp/GC | abc523e7038a7d2c383e5c2fe8d9ab72f3bb9a7d | ä¸é¨ã®é¢æ°ãåé¢ãã | diff --git a/GC.v b/GC.v
index 13ddd22..259268d 100644
--- a/GC.v
+++ b/GC.v
@@ -1,76 +1,75 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
+Require Import Util.
(** * operations of set *)
Definition In {A : Type} (elem : A) (sets : set A) :=
set_In elem sets.
Definition Included {A : Type} (B C : set A) : Prop :=
forall x, In x B -> In x C.
-Definition x_dec A :=
- forall x y : A, {x = y} + {x <> y}.
Definition Union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
set_union dec B C.
(** * Memory *)
Inductive mark :=
| Marked : mark
| Unmarked : mark.
Definition mark_dec : forall (m1 m2 : mark), { m1 = m2} + { m1 <> m2}.
Proof.
decide equality.
Qed.
Record Mem {A : Type} := mkMem {
roots : set A; (** root objects *)
nodes : set A; (** all objects in memory *)
frees : set A; (** free list *)
marker : A -> mark; (** get mark of the object *)
pointer : A -> option A (** get next object of the object *)
}.
(** * GC *)
(** ** closure *)
(** [Closure A next x] means a set: {x, next x, next (next x), ... }. *)
Inductive Connect (A : Type) (next : A -> option A) (root : A) : A -> Prop:=
| CRoot :
Connect A next root root
| CTrans : forall x y,
Some y = next x -> Connect A next y x -> Connect A next root x.
Inductive ConnectS (A : Type) (next : A -> option A) (roots : set A) : A -> Prop :=
| ConnectSet_intro : forall n m,
In m roots -> Connect A next m n -> ConnectS A next roots n.
Definition ConnectM {A : Type} (m : Mem) :=
ConnectS A (pointer m) (roots m).
(** ** Marker utility *)
Definition marks (A : Type) (marker : A -> mark) (ma : mark) (xs : set A) : set A :=
filter (fun x => if mark_dec (marker x) ma then true else false) xs.
Definition marksM {A : Type} (ma : mark) (m : Mem) :=
marks A (marker m) ma (nodes m).
(** ** main GC *)
(** marker *)
Definition Marker {A : Type} (m1 m2 : Mem (A:=A)) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
frees m1 = frees m2 /\
pointer m1 = pointer m2 /\
forall x, ConnectM m2 x -> marker m2 x = Marked.
(** sweeper *)
Definition Sweeper {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
pointer m1 = pointer m2 /\
frees m2 = Union dec (frees m1) (marksM Unmarked m1) /\
forall (n : A), In n (nodes m2) -> marker m2 n = Unmarked.
(** mark & sweep GC *)
Definition GC {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) := exists m : Mem,
Marker m1 m /\ Sweeper dec m m2.
diff --git a/GC_fact.v b/GC_fact.v
index 9dc8c60..b16431d 100644
--- a/GC_fact.v
+++ b/GC_fact.v
@@ -1,148 +1,149 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
+Require Import Util.
Require Import GC.
(** invariant *)
Definition invariant {A : Type} (m : Mem) : Prop :=
Included (roots m) (nodes m) /\
Included (frees m) (nodes m) /\
forall (x y :A), In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
Lemma marker_invariant : forall A (m1 m2 : Mem (A:=A)),
Marker m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Marker, invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <-H1, <-H2, <-H3, <-H4.
repeat split; auto.
Qed.
Lemma Marks_include : forall A xs marker m,
Included (marks A marker m xs) xs.
Proof.
unfold Included, marks, In, set_In.
intros.
apply filter_In in H.
decompose [and] H.
tauto.
Qed.
Lemma sweeper_invariant: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Sweeper dec m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Sweeper, invariant, Union.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <- H1, <- H2, <- H3, H4.
repeat split; auto.
unfold Included.
intros.
unfold In in H7.
apply set_union_elim in H7.
decompose [or] H7.
apply H8 in H10.
tauto.
apply (Marks_include _ _ (marker m1) Unmarked _).
tauto.
Qed.
Theorem gc_invariant : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
invariant m1 -> GC dec m1 m2 -> invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_invariant in H2; auto.
apply sweeper_invariant in H3; auto.
Qed.
(** safety *)
Definition disjoint (P Q : Prop) :=
(P -> ~ Q) /\ (Q -> ~ P).
Definition Safety {A : Type} (m : Mem) : Prop := forall x : A,
disjoint (In x (frees m)) (ConnectM m x).
Definition MarksAll {A : Type} (m : Mem) : Prop := forall x : A,
disjoint (In x (marksM Unmarked m)) (ConnectM m x).
Lemma sweeper_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety m1 -> MarksAll m1 -> Sweeper dec m1 m2 -> Safety m2.
Proof.
unfold Safety, MarksAll, Sweeper, ConnectM, disjoint, Union, In.
intros.
decompose [and] (H x).
decompose [and] (H0 x).
decompose [and] H1.
rewrite <- H6, <- H7, H9.
split; intros.
apply set_union_elim in H10.
decompose [or] H10.
apply H2 in H12.
tauto.
apply H4 in H12.
tauto.
intro.
apply set_union_elim in H12.
decompose [or] H12.
apply H2 in H13.
contradiction.
apply H4 in H13.
contradiction.
Qed.
Lemma marker_safety : forall A (m1 m2 : Mem (A:=A)),
Safety m1 -> Marker m1 m2 -> Safety m2 /\ MarksAll m2.
Proof.
unfold Safety, MarksAll, Marker, ConnectM, disjoint, Union, In.
intros.
decompose [and] H0.
rewrite <- H1, <- H2, <- H4.
rewrite <- H1, <-H4 in H6.
repeat split; intros; decompose [and] (H x); intro.
apply H8 in H9.
contradiction.
apply H7 in H9.
contradiction.
generalize H9; intro.
apply (H6 x) in H9.
unfold marksM, marks in H5.
apply filter_In in H5.
decompose [and] H5.
destruct (mark_dec (marker m2 x)).
rewrite H9 in e.
discriminate.
discriminate.
apply H6 in H5.
unfold marksM, marks in H9.
apply filter_In in H9.
decompose [and] H9.
destruct (mark_dec (marker m2 x)).
rewrite H5 in e.
discriminate.
discriminate.
Qed.
Theorem gc_safety: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety m1 -> GC dec m1 m2 -> Safety m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_safety in H2; auto.
decompose [and] H2.
apply sweeper_safety in H3; auto.
Qed.
diff --git a/OMakefile b/OMakefile
index cf719b3..45e4465 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,16 +1,17 @@
FILES[] =
+ Util
GC
GC_fact
.PHONY: clean graph doc all
.DEFAULT: all
all: $(CoqProof $(FILES))
clean:
rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock
doc: $(addsuffix .v, $(FILES))
mkdir -p doc
coqdoc -d doc *.v
diff --git a/Util.v b/Util.v
new file mode 100644
index 0000000..a2dec9a
--- /dev/null
+++ b/Util.v
@@ -0,0 +1,2 @@
+Definition x_dec A :=
+ forall x y : A, {x = y} + {x <> y}.
\ No newline at end of file
|
mzp/GC | 60b89e327b5862462f029620e58e293603a93a06 | ãã¡ã¤ã«åå² | diff --git a/GC.v b/GC.v
new file mode 100644
index 0000000..13ddd22
--- /dev/null
+++ b/GC.v
@@ -0,0 +1,76 @@
+(* -#- mode:coq coding:utf-8 -#- *)
+Require Import Lists.ListSet.
+Require Import Lists.List.
+
+(** * operations of set *)
+Definition In {A : Type} (elem : A) (sets : set A) :=
+ set_In elem sets.
+Definition Included {A : Type} (B C : set A) : Prop :=
+ forall x, In x B -> In x C.
+Definition x_dec A :=
+ forall x y : A, {x = y} + {x <> y}.
+Definition Union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
+ set_union dec B C.
+
+(** * Memory *)
+Inductive mark :=
+ | Marked : mark
+ | Unmarked : mark.
+
+Definition mark_dec : forall (m1 m2 : mark), { m1 = m2} + { m1 <> m2}.
+Proof.
+decide equality.
+Qed.
+
+Record Mem {A : Type} := mkMem {
+ roots : set A; (** root objects *)
+ nodes : set A; (** all objects in memory *)
+ frees : set A; (** free list *)
+ marker : A -> mark; (** get mark of the object *)
+ pointer : A -> option A (** get next object of the object *)
+}.
+
+(** * GC *)
+
+(** ** closure *)
+(** [Closure A next x] means a set: {x, next x, next (next x), ... }. *)
+Inductive Connect (A : Type) (next : A -> option A) (root : A) : A -> Prop:=
+ | CRoot :
+ Connect A next root root
+ | CTrans : forall x y,
+ Some y = next x -> Connect A next y x -> Connect A next root x.
+
+Inductive ConnectS (A : Type) (next : A -> option A) (roots : set A) : A -> Prop :=
+ | ConnectSet_intro : forall n m,
+ In m roots -> Connect A next m n -> ConnectS A next roots n.
+
+Definition ConnectM {A : Type} (m : Mem) :=
+ ConnectS A (pointer m) (roots m).
+
+(** ** Marker utility *)
+Definition marks (A : Type) (marker : A -> mark) (ma : mark) (xs : set A) : set A :=
+ filter (fun x => if mark_dec (marker x) ma then true else false) xs.
+
+Definition marksM {A : Type} (ma : mark) (m : Mem) :=
+ marks A (marker m) ma (nodes m).
+
+(** ** main GC *)
+(** marker *)
+Definition Marker {A : Type} (m1 m2 : Mem (A:=A)) : Prop :=
+ roots m1 = roots m2 /\
+ nodes m1 = nodes m2 /\
+ frees m1 = frees m2 /\
+ pointer m1 = pointer m2 /\
+ forall x, ConnectM m2 x -> marker m2 x = Marked.
+
+(** sweeper *)
+Definition Sweeper {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
+ roots m1 = roots m2 /\
+ nodes m1 = nodes m2 /\
+ pointer m1 = pointer m2 /\
+ frees m2 = Union dec (frees m1) (marksM Unmarked m1) /\
+ forall (n : A), In n (nodes m2) -> marker m2 n = Unmarked.
+
+(** mark & sweep GC *)
+Definition GC {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) := exists m : Mem,
+ Marker m1 m /\ Sweeper dec m m2.
diff --git a/object.v b/GC_fact.v
similarity index 58%
rename from object.v
rename to GC_fact.v
index ab6784e..9dc8c60 100644
--- a/object.v
+++ b/GC_fact.v
@@ -1,220 +1,148 @@
(* -#- mode:coq coding:utf-8 -#- *)
Require Import Lists.ListSet.
Require Import Lists.List.
+Require Import GC.
-(** * operations of set *)
-Definition In {A : Type} (elem : A) (sets : set A) :=
- set_In elem sets.
-Definition Included {A : Type} (B C : set A) : Prop :=
- forall x, In x B -> In x C.
-Definition x_dec A :=
- forall x y : A, {x = y} + {x <> y}.
-Definition Union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
- set_union dec B C.
-
-(** * Memory *)
-Inductive mark :=
- | Marked : mark
- | Unmarked : mark.
-Definition mark_dec : forall (m1 m2 : mark), { m1 = m2} + { m1 <> m2}.
-Proof.
-decide equality.
-Qed.
-
-Record Mem {A : Type} := mkMem {
- roots : set A; (** root objects *)
- nodes : set A; (** all objects in memory *)
- frees : set A; (** free list *)
- marker : A -> mark; (** get mark of the object *)
- pointer : A -> option A (** get next object of the object *)
-}.
-
-(** * GC *)
-
-(** ** closure *)
-(** [Closure A next x] means a set: {x, next x, next (next x), ... }. *)
-Inductive Connect (A : Type) (next : A -> option A) (root : A) : A -> Prop:=
- | CRoot :
- Connect A next root root
- | CTrans : forall x y,
- Some y = next x -> Connect A next y x -> Connect A next root x.
-
-Inductive ConnectS (A : Type) (next : A -> option A) (roots : set A) : A -> Prop :=
- | ConnectSet_intro : forall n m,
- In m roots -> Connect A next m n -> ConnectS A next roots n.
-
-Definition ConnectM {A : Type} (m : Mem) :=
- ConnectS A (pointer m) (roots m).
-
-(** ** Marker utility *)
-Definition marks (A : Type) (marker : A -> mark) (ma : mark) (xs : set A) : set A :=
- filter (fun x => if mark_dec (marker x) ma then true else false) xs.
-
-Definition marksM {A : Type} (ma : mark) (m : Mem) :=
- marks A (marker m) ma (nodes m).
-
-(** ** main GC *)
-(** marker *)
-Definition Marker {A : Type} (m1 m2 : Mem (A:=A)) : Prop :=
- roots m1 = roots m2 /\
- nodes m1 = nodes m2 /\
- frees m1 = frees m2 /\
- pointer m1 = pointer m2 /\
- forall x, ConnectM m2 x -> marker m2 x = Marked.
-
-(** sweeper *)
-Definition Sweeper {A : Type} (dec : x_dec A) (m1 m2 : Mem) : Prop :=
- roots m1 = roots m2 /\
- nodes m1 = nodes m2 /\
- pointer m1 = pointer m2 /\
- frees m2 = Union dec (frees m1) (marksM Unmarked m1) /\
- forall (n : A), In n (nodes m2) -> marker m2 n = Unmarked.
-
-(** mark & sweep GC *)
-Definition GC {A : Type} (dec : x_dec A) (m1 m2 : Mem (A:=A)) := exists m : Mem,
- Marker m1 m /\ Sweeper dec m m2.
-
-(** * Spec *)
(** invariant *)
Definition invariant {A : Type} (m : Mem) : Prop :=
Included (roots m) (nodes m) /\
Included (frees m) (nodes m) /\
forall (x y :A), In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
Lemma marker_invariant : forall A (m1 m2 : Mem (A:=A)),
Marker m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Marker, invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <-H1, <-H2, <-H3, <-H4.
repeat split; auto.
Qed.
Lemma Marks_include : forall A xs marker m,
Included (marks A marker m xs) xs.
Proof.
unfold Included, marks, In, set_In.
intros.
apply filter_In in H.
decompose [and] H.
tauto.
Qed.
Lemma sweeper_invariant: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Sweeper dec m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Sweeper, invariant, Union.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <- H1, <- H2, <- H3, H4.
repeat split; auto.
unfold Included.
intros.
unfold In in H7.
apply set_union_elim in H7.
decompose [or] H7.
apply H8 in H10.
tauto.
apply (Marks_include _ _ (marker m1) Unmarked _).
tauto.
Qed.
Theorem gc_invariant : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
invariant m1 -> GC dec m1 m2 -> invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_invariant in H2; auto.
apply sweeper_invariant in H3; auto.
Qed.
(** safety *)
Definition disjoint (P Q : Prop) :=
(P -> ~ Q) /\ (Q -> ~ P).
Definition Safety {A : Type} (m : Mem) : Prop := forall x : A,
disjoint (In x (frees m)) (ConnectM m x).
Definition MarksAll {A : Type} (m : Mem) : Prop := forall x : A,
disjoint (In x (marksM Unmarked m)) (ConnectM m x).
Lemma sweeper_safety : forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety m1 -> MarksAll m1 -> Sweeper dec m1 m2 -> Safety m2.
Proof.
unfold Safety, MarksAll, Sweeper, ConnectM, disjoint, Union, In.
intros.
decompose [and] (H x).
decompose [and] (H0 x).
decompose [and] H1.
rewrite <- H6, <- H7, H9.
split; intros.
apply set_union_elim in H10.
decompose [or] H10.
apply H2 in H12.
tauto.
apply H4 in H12.
tauto.
intro.
apply set_union_elim in H12.
decompose [or] H12.
apply H2 in H13.
contradiction.
apply H4 in H13.
contradiction.
Qed.
Lemma marker_safety : forall A (m1 m2 : Mem (A:=A)),
Safety m1 -> Marker m1 m2 -> Safety m2 /\ MarksAll m2.
Proof.
unfold Safety, MarksAll, Marker, ConnectM, disjoint, Union, In.
intros.
decompose [and] H0.
rewrite <- H1, <- H2, <- H4.
rewrite <- H1, <-H4 in H6.
repeat split; intros; decompose [and] (H x); intro.
apply H8 in H9.
contradiction.
apply H7 in H9.
contradiction.
generalize H9; intro.
apply (H6 x) in H9.
unfold marksM, marks in H5.
apply filter_In in H5.
decompose [and] H5.
destruct (mark_dec (marker m2 x)).
rewrite H9 in e.
discriminate.
discriminate.
apply H6 in H5.
unfold marksM, marks in H9.
apply filter_In in H9.
decompose [and] H9.
destruct (mark_dec (marker m2 x)).
rewrite H5 in e.
discriminate.
discriminate.
Qed.
Theorem gc_safety: forall A (dec : x_dec A) (m1 m2 : Mem (A:=A)),
Safety m1 -> GC dec m1 m2 -> Safety m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0; auto.
apply marker_safety in H2; auto.
decompose [and] H2.
apply sweeper_safety in H3; auto.
Qed.
diff --git a/OMakefile b/OMakefile
index 51bfb7f..cf719b3 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,15 +1,16 @@
FILES[] =
- object
+ GC
+ GC_fact
.PHONY: clean graph doc all
.DEFAULT: all
all: $(CoqProof $(FILES))
clean:
rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock
doc: $(addsuffix .v, $(FILES))
mkdir -p doc
coqdoc -d doc *.v
|
mzp/GC | f0880f29df19a72fe2ad4b316548f6cdcc305994 | 証æãæ´çãã | diff --git a/OMakefile b/OMakefile
index f1e4405..51bfb7f 100644
--- a/OMakefile
+++ b/OMakefile
@@ -1,10 +1,15 @@
FILES[] =
object
-.DEFAULT: $(CoqProof $(FILES))
+.PHONY: clean graph doc all
+.DEFAULT: all
-.PHONY: clean graph
+all: $(CoqProof $(FILES))
clean:
rm -rf *.vo *.glob *~ *.omc .omakedb .omakedb.lock
+doc: $(addsuffix .v, $(FILES))
+ mkdir -p doc
+ coqdoc -d doc *.v
+
diff --git a/object.v b/object.v
index dd3cfcc..ac5aeac 100644
--- a/object.v
+++ b/object.v
@@ -1,192 +1,197 @@
Require Import Sets.Ensembles.
-(* operations of set *)
+(** * operations of set *)
Definition set A := Ensemble A.
Definition In {A : Type} elem sets := Sets.Ensembles.In A sets elem.
Implicit Arguments Sets.Ensembles.Included [U].
Implicit Arguments Sets.Ensembles.Union [U].
-(* definition of memory *)
+(** * Memory *)
Inductive mark :=
| Marked : mark
| Unmarked : mark.
Record Mem {A : Type} := mkMem {
- roots : set A; (* root objects *)
- nodes : set A; (* all objects in memory *)
- frees : set A; (* free list *)
- marker : A -> mark; (* get mark of the object *)
- pointer : A -> option A (* get next object of the object *)
+ roots : set A; (** root objects *)
+ nodes : set A; (** all objects in memory *)
+ frees : set A; (** free list *)
+ marker : A -> mark; (** get mark of the object *)
+ pointer : A -> option A (** get next object of the object *)
}.
-(* Definition of GC *)
+(** * GC *)
-(* [Closure A next x] means a set: {x, next x, next (next x), ... }. *)
+(** ** closure *)
+(** [Closure A next x] means a set: {x, next x, next (next x), ... }. *)
Inductive Closure (A : Type) (next : A -> option A) : A -> set A :=
| CRoot : forall x,
In x (Closure A next x)
| CTrans : forall x y z,
Some y = next x -> In z (Closure A next y) -> In z (Closure A next x).
Inductive Closures (A : Type) (next : A -> option A) (roots : set A) : set A :=
| Closures_intro : forall n m,
In m roots -> In n (Closure A next m) -> In n (Closures A next roots).
Implicit Arguments Closures [A].
+Definition ClosuresM {A : Type} (m : Mem) :=
+ Closures (A:=A) (pointer m) (roots m).
+
+(** ** Marker utility *)
Inductive Marks (A : Type) (marker : A -> mark) (m : mark) (xs : set A) : set A :=
- | Marks_intro : forall x, In x xs -> marker x = m -> In x (Marks A marker m xs).
+ | Marks_intro : forall x,
+ In x xs -> marker x = m -> In x (Marks A marker m xs).
+
+Definition MarksM {A : Type} (ma : mark) (m : Mem) :=
+ Marks A (marker m) ma (nodes m).
-Definition Marker {A : Type} (m1 m2 : Mem) : Prop :=
+(** ** main GC *)
+(** marker *)
+Definition Marker {A : Type} (m1 m2 : Mem (A:=A)) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
frees m1 = frees m2 /\
pointer m1 = pointer m2 /\
- Included (Closures (pointer m2) (roots m2)) (Marks A (marker m2) Marked (nodes m2)).
+ Included (ClosuresM m2) (MarksM Marked m2).
+(** sweeper *)
Definition Sweeper {A : Type} (m1 m2 : Mem) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
pointer m1 = pointer m2 /\
- frees m2 = Union (frees m1) (Marks A (marker m1) Unmarked (nodes m1)) /\
- forall n, In n (nodes m2) -> marker m2 n = Unmarked.
+ frees m2 = Union (frees m1) (MarksM Unmarked m1) /\
+ forall (n : A), In n (nodes m2) -> marker m2 n = Unmarked.
+
+(** mark & sweep GC *)
+Definition GC {A : Type} (m1 m2 : Mem (A:=A)) := exists m : Mem,
+ Marker m1 m /\ Sweeper m m2.
+(** * Spec *)
+(** invariant *)
Definition invariant {A : Type} (m : Mem) : Prop :=
Included (roots m) (nodes m) /\
Included (frees m) (nodes m) /\
forall (x y :A), In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
Lemma marker_invariant : forall A (m1 m2 : Mem (A:=A)),
Marker m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Marker, invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <-H1, <-H2, <-H3, <-H4.
repeat split; auto.
Qed.
Lemma Marks_include : forall A xs marker m,
Included (Marks A marker m xs) xs.
Proof.
unfold Included.
intros.
inversion H.
tauto.
Qed.
Lemma sweeper_invariant: forall A (m1 m2 : Mem (A:=A)),
Sweeper m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Sweeper, invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <- H1, <- H2, <- H3, H4.
repeat split; auto.
unfold Included.
intros.
inversion H7; auto.
generalize Marks_include.
intros.
unfold Included in H12.
apply (H12 _ _ (marker m1) Unmarked _).
tauto.
Qed.
-Definition frees_invariant {A : Type} (m : Mem) :=
+Theorem gc_invariant : forall A (m1 m2 : Mem (A:=A)),
+ invariant m1 -> GC m1 m2 -> invariant m2.
+Proof.
+unfold GC.
+intros.
+decompose [ex and] H0; auto.
+apply marker_invariant in H2; auto.
+apply sweeper_invariant in H3; auto.
+Qed.
+
+(** safety *)
+Definition Safety {A : Type} (m : Mem) : Prop :=
Disjoint A (frees m) (Closures (pointer m) (roots m)).
-Definition marks_all {A : Type} (m : Mem) :=
- Disjoint A (Marks A (marker m) Unmarked (nodes m)) (Closures (pointer m) (roots m)).
+Definition MarksAll {A : Type} (m : Mem) : Prop :=
+ Disjoint A (Marks A (marker m) Unmarked (nodes m))
+ (Closures (pointer m) (roots m)).
-Lemma sweeper_frees : forall A (m1 m2 : Mem (A:=A)),
- frees_invariant m1 -> marks_all m1 -> Sweeper m1 m2 -> frees_invariant m2.
+Lemma sweeper_safety : forall A (m1 m2 : Mem (A:=A)),
+ Safety m1 -> MarksAll m1 -> Sweeper m1 m2 -> Safety m2.
Proof.
-unfold frees_invariant, marks_all, Sweeper.
+unfold Safety, MarksAll, Sweeper.
intros.
decompose [and] H1.
rewrite <- H2, <- H3, H5.
apply Disjoint_intro; intros.
inversion H.
inversion H0.
specialize (H6 x).
specialize (H8 x).
intro.
inversion H9.
inversion H10.
apply H6.
apply Intersection_intro; auto.
apply H8.
apply Intersection_intro; auto.
Qed.
Lemma disjoint_include: forall A (B C D : set A),
Disjoint A B C -> Included D C -> Disjoint A B D.
Proof.
intros.
inversion H.
apply Disjoint_intro; intros.
intro.
apply (H1 x).
inversion H2.
apply Intersection_intro; auto.
Qed.
-
-Lemma marker_frees : forall A (m1 m2 : Mem (A:=A)),
- frees_invariant m1 -> Marker m1 m2 -> frees_invariant m2 /\ marks_all m2.
+Lemma marker_safety : forall A (m1 m2 : Mem (A:=A)),
+ Safety m1 -> Marker m1 m2 -> Safety m2 /\ MarksAll m2.
Proof.
-unfold frees_invariant, Marker, marks_all.
+unfold Safety, Marker, MarksAll.
split; intros.
decompose [and] H0.
rewrite <- H1, <- H2, <- H4.
tauto.
decompose [and] H0.
apply (disjoint_include _ _ (Marks A (marker m2) Marked (nodes m2))); auto.
apply Disjoint_intro.
intros.
intro.
inversion H5.
inversion H7.
inversion H8.
rewrite H11 in H14.
inversion H14.
Qed.
-Definition GC {A : Type} (m1 m2 : Mem (A:=A)) := exists m : Mem,
- Marker m1 m /\ Sweeper m m2.
-Theorem gc_invariant : forall A (m1 m2 : Mem (A:=A)),
- invariant m1 -> GC m1 m2 -> invariant m2.
-Proof.
-unfold GC.
-intros.
-decompose [ex and] H0.
- apply marker_invariant in H2.
- apply sweeper_invariant in H3.
- tauto.
-
- tauto.
-
- tauto.
-Qed.
-
-Theorem gc_free: forall A (m1 m2 : Mem (A:=A)),
- frees_invariant m1 -> GC m1 m2 -> frees_invariant m2.
+Theorem gc_safety: forall A (m1 m2 : Mem (A:=A)),
+ Safety m1 -> GC m1 m2 -> Safety m2.
Proof.
unfold GC.
intros.
-decompose [ex and] H0.
- apply marker_frees in H2.
- decompose [and] H2.
- apply sweeper_frees in H3.
- tauto.
-
- tauto.
-
- tauto.
-
- tauto.
+decompose [ex and] H0; auto.
+apply marker_safety in H2; auto.
+decompose [and] H2.
+apply sweeper_safety in H3; auto.
Qed.
|
mzp/GC | 939c5c72ea96524385dc04803b6d2e6a66b8ecf3 | add implicit parameter to mkMem | diff --git a/object.v b/object.v
index df3bbf5..dd3cfcc 100644
--- a/object.v
+++ b/object.v
@@ -1,192 +1,192 @@
-Require Import Sets.Finite_sets.
Require Import Sets.Ensembles.
-Inductive mark :=
- | Marked : mark
- | Unmarked : mark.
+(* operations of set *)
+Definition set A := Ensemble A.
Definition In {A : Type} elem sets := Sets.Ensembles.In A sets elem.
Implicit Arguments Sets.Ensembles.Included [U].
-Implicit Arguments Sets.Ensembles.Add [U].
Implicit Arguments Sets.Ensembles.Union [U].
-Implicit Arguments Sets.Ensembles.Intersection [U].
-Implicit Arguments Sets.Finite_sets.Finite [U].
-
-Record Mem (A : Type) := mkMem {
- roots : Ensemble A;
- nodes : Ensemble A;
- frees : Ensemble A;
- marker : A -> mark;
- pointer : A -> option A
+
+(* definition of memory *)
+Inductive mark :=
+ | Marked : mark
+ | Unmarked : mark.
+
+Record Mem {A : Type} := mkMem {
+ roots : set A; (* root objects *)
+ nodes : set A; (* all objects in memory *)
+ frees : set A; (* free list *)
+ marker : A -> mark; (* get mark of the object *)
+ pointer : A -> option A (* get next object of the object *)
}.
-Implicit Arguments roots [A].
-Implicit Arguments nodes [A].
-Implicit Arguments frees [A].
-Implicit Arguments marker [A].
-Implicit Arguments pointer [A].
-Implicit Arguments mkMem [A].
-
-Inductive Closure (A : Type) (pointer : A -> option A) (root : A) : Ensemble A :=
- | CRefl : In root (Closure A pointer root)
- | CTrans : forall n m, Some n = pointer root -> In m (Closure A pointer n) -> In m (Closure A pointer root).
-
-Inductive Closures (A : Type) (pointer : A -> option A) (roots : Ensemble A) : Ensemble A :=
- | Closures_intro : forall n m, In m roots -> In n (Closure A pointer m) -> In n (Closures A pointer roots).
+
+(* Definition of GC *)
+
+(* [Closure A next x] means a set: {x, next x, next (next x), ... }. *)
+Inductive Closure (A : Type) (next : A -> option A) : A -> set A :=
+ | CRoot : forall x,
+ In x (Closure A next x)
+ | CTrans : forall x y z,
+ Some y = next x -> In z (Closure A next y) -> In z (Closure A next x).
+
+Inductive Closures (A : Type) (next : A -> option A) (roots : set A) : set A :=
+ | Closures_intro : forall n m,
+ In m roots -> In n (Closure A next m) -> In n (Closures A next roots).
Implicit Arguments Closures [A].
-Inductive Marks (A : Type) (marker : A -> mark) (m : mark) (xs : Ensemble A) : Ensemble A :=
+Inductive Marks (A : Type) (marker : A -> mark) (m : mark) (xs : set A) : set A :=
| Marks_intro : forall x, In x xs -> marker x = m -> In x (Marks A marker m xs).
-Definition Marker {A : Type} (m1 m2 : Mem A) : Prop :=
+Definition Marker {A : Type} (m1 m2 : Mem) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
frees m1 = frees m2 /\
pointer m1 = pointer m2 /\
Included (Closures (pointer m2) (roots m2)) (Marks A (marker m2) Marked (nodes m2)).
-Definition Sweeper {A : Type} (m1 m2 : Mem A) : Prop :=
+Definition Sweeper {A : Type} (m1 m2 : Mem) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
pointer m1 = pointer m2 /\
frees m2 = Union (frees m1) (Marks A (marker m1) Unmarked (nodes m1)) /\
forall n, In n (nodes m2) -> marker m2 n = Unmarked.
-Definition invariant {A : Type} (m : Mem A) : Prop :=
+Definition invariant {A : Type} (m : Mem) : Prop :=
Included (roots m) (nodes m) /\
Included (frees m) (nodes m) /\
- forall x y, In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
+ forall (x y :A), In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
-Lemma marker_invariant : forall A (m1 m2 : Mem A),
+Lemma marker_invariant : forall A (m1 m2 : Mem (A:=A)),
Marker m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Marker, invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <-H1, <-H2, <-H3, <-H4.
repeat split; auto.
Qed.
Lemma Marks_include : forall A xs marker m,
Included (Marks A marker m xs) xs.
Proof.
unfold Included.
intros.
inversion H.
tauto.
Qed.
-Lemma sweeper_invariant: forall A (m1 m2 : Mem A),
+Lemma sweeper_invariant: forall A (m1 m2 : Mem (A:=A)),
Sweeper m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Sweeper, invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <- H1, <- H2, <- H3, H4.
repeat split; auto.
unfold Included.
intros.
inversion H7; auto.
generalize Marks_include.
intros.
unfold Included in H12.
apply (H12 _ _ (marker m1) Unmarked _).
tauto.
Qed.
-Definition frees_invariant {A : Type} (m : Mem A) :=
+Definition frees_invariant {A : Type} (m : Mem) :=
Disjoint A (frees m) (Closures (pointer m) (roots m)).
-Definition marks_all {A : Type} (m : Mem A) :=
+Definition marks_all {A : Type} (m : Mem) :=
Disjoint A (Marks A (marker m) Unmarked (nodes m)) (Closures (pointer m) (roots m)).
-Lemma sweeper_frees : forall A (m1 m2 : Mem A),
+Lemma sweeper_frees : forall A (m1 m2 : Mem (A:=A)),
frees_invariant m1 -> marks_all m1 -> Sweeper m1 m2 -> frees_invariant m2.
Proof.
unfold frees_invariant, marks_all, Sweeper.
intros.
decompose [and] H1.
rewrite <- H2, <- H3, H5.
apply Disjoint_intro; intros.
inversion H.
inversion H0.
specialize (H6 x).
specialize (H8 x).
intro.
inversion H9.
inversion H10.
apply H6.
apply Intersection_intro; auto.
apply H8.
apply Intersection_intro; auto.
Qed.
-Lemma disjoint_include: forall A (B C D : Ensemble A),
+Lemma disjoint_include: forall A (B C D : set A),
Disjoint A B C -> Included D C -> Disjoint A B D.
Proof.
intros.
inversion H.
apply Disjoint_intro; intros.
intro.
apply (H1 x).
inversion H2.
apply Intersection_intro; auto.
Qed.
-Lemma marker_frees : forall A (m1 m2 : Mem A),
+Lemma marker_frees : forall A (m1 m2 : Mem (A:=A)),
frees_invariant m1 -> Marker m1 m2 -> frees_invariant m2 /\ marks_all m2.
Proof.
unfold frees_invariant, Marker, marks_all.
split; intros.
decompose [and] H0.
rewrite <- H1, <- H2, <- H4.
tauto.
decompose [and] H0.
apply (disjoint_include _ _ (Marks A (marker m2) Marked (nodes m2))); auto.
apply Disjoint_intro.
intros.
intro.
inversion H5.
inversion H7.
inversion H8.
rewrite H11 in H14.
inversion H14.
Qed.
-Definition GC {A : Type} (m1 m2 : Mem A) := exists m : Mem A,
+Definition GC {A : Type} (m1 m2 : Mem (A:=A)) := exists m : Mem,
Marker m1 m /\ Sweeper m m2.
-Theorem gc_invariant : forall A (m1 m2 : Mem A),
+Theorem gc_invariant : forall A (m1 m2 : Mem (A:=A)),
invariant m1 -> GC m1 m2 -> invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0.
apply marker_invariant in H2.
apply sweeper_invariant in H3.
tauto.
tauto.
tauto.
Qed.
-Theorem gc_free: forall A (m1 m2 : Mem A),
+Theorem gc_free: forall A (m1 m2 : Mem (A:=A)),
frees_invariant m1 -> GC m1 m2 -> frees_invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0.
apply marker_frees in H2.
decompose [and] H2.
apply sweeper_frees in H3.
tauto.
tauto.
tauto.
tauto.
Qed.
|
mzp/GC | 470afb164d9f4dcb7638ced5131f546524db167c | ListSetã使ã£ã¦æ¸ãç´ãã¦ãæä¸ | diff --git a/object.v b/object.v
index df3bbf5..a946195 100644
--- a/object.v
+++ b/object.v
@@ -1,192 +1,207 @@
-Require Import Sets.Finite_sets.
-Require Import Sets.Ensembles.
+(* -#- mode:coq coding:utf-8 -#- *)
+Require Import Lists.ListSet.
+
+(* éåã«å¯¾ããæä½ *)
+Definition In {A : Type} (elem : A) (sets : set A) :=
+ set_In elem sets.
+Definition Included {A : Type} (B C : set A) : Prop :=
+ forall x, In x B -> In x C.
+Definition x_dec A :=
+ forall x y : A, {x = y} + {x <> y}.
+Definition Union {A : Type} (dec : x_dec A) (B C : set A) : set A :=
+ set_union dec B C.
+
+(* ã¡ã¢ãªã®å®ç¾© *)
Inductive mark :=
- | Marked : mark
+ | Marked : mark
| Unmarked : mark.
-Definition In {A : Type} elem sets := Sets.Ensembles.In A sets elem.
-Implicit Arguments Sets.Ensembles.Included [U].
-Implicit Arguments Sets.Ensembles.Add [U].
-Implicit Arguments Sets.Ensembles.Union [U].
-Implicit Arguments Sets.Ensembles.Intersection [U].
-Implicit Arguments Sets.Finite_sets.Finite [U].
-
-Record Mem (A : Type) := mkMem {
- roots : Ensemble A;
- nodes : Ensemble A;
- frees : Ensemble A;
+Record Mem {A : Type} := mkMem {
+ roots : set A;
+ nodes : set A;
+ frees : set A;
marker : A -> mark;
pointer : A -> option A
}.
-Implicit Arguments roots [A].
-Implicit Arguments nodes [A].
-Implicit Arguments frees [A].
-Implicit Arguments marker [A].
+(*Implicit Arguments roots [A].
+Implicit Arguments nodes [A].
+Implicit Arguments frees [A].
+Implicit Arguments marker [A].
Implicit Arguments pointer [A].
-Implicit Arguments mkMem [A].
-
-Inductive Closure (A : Type) (pointer : A -> option A) (root : A) : Ensemble A :=
- | CRefl : In root (Closure A pointer root)
- | CTrans : forall n m, Some n = pointer root -> In m (Closure A pointer n) -> In m (Closure A pointer root).
+Implicit Arguments mkMem [A].
+*)
-Inductive Closures (A : Type) (pointer : A -> option A) (roots : Ensemble A) : Ensemble A :=
+Require Import Sets.Ensembles.
+Check set.
+Check Ensemble.
+Print Ensemble.
+Print set.
+Inductive Closure : forall (A : Type), (A -> option A) -> A -> set A :=
+ | CRefl : forall A f x,
+ In x (Closure A f x).
+(* | CTrans :
+ forall n m, Some n = pointer root ->
+ In m (Closure A pointer n) ->
+ In m (Closure A pointer root).*)
+
+Inductive Closures (A : Type) (pointer : A -> option A) (roots : set A) : set A :=
| Closures_intro : forall n m, In m roots -> In n (Closure A pointer m) -> In n (Closures A pointer roots).
Implicit Arguments Closures [A].
-Inductive Marks (A : Type) (marker : A -> mark) (m : mark) (xs : Ensemble A) : Ensemble A :=
+Inductive Marks (A : Type) (marker : A -> mark) (m : mark) (xs : set A) : set A :=
| Marks_intro : forall x, In x xs -> marker x = m -> In x (Marks A marker m xs).
Definition Marker {A : Type} (m1 m2 : Mem A) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
frees m1 = frees m2 /\
pointer m1 = pointer m2 /\
Included (Closures (pointer m2) (roots m2)) (Marks A (marker m2) Marked (nodes m2)).
Definition Sweeper {A : Type} (m1 m2 : Mem A) : Prop :=
roots m1 = roots m2 /\
nodes m1 = nodes m2 /\
pointer m1 = pointer m2 /\
frees m2 = Union (frees m1) (Marks A (marker m1) Unmarked (nodes m1)) /\
forall n, In n (nodes m2) -> marker m2 n = Unmarked.
Definition invariant {A : Type} (m : Mem A) : Prop :=
Included (roots m) (nodes m) /\
Included (frees m) (nodes m) /\
forall x y, In x (nodes m) -> Some y = pointer m x -> In y (nodes m).
Lemma marker_invariant : forall A (m1 m2 : Mem A),
Marker m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Marker, invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <-H1, <-H2, <-H3, <-H4.
repeat split; auto.
Qed.
Lemma Marks_include : forall A xs marker m,
Included (Marks A marker m xs) xs.
Proof.
unfold Included.
intros.
inversion H.
tauto.
Qed.
Lemma sweeper_invariant: forall A (m1 m2 : Mem A),
Sweeper m1 m2 -> invariant m1 -> invariant m2.
Proof.
unfold Sweeper, invariant.
intros.
decompose [and] H.
decompose [and] H0.
rewrite <- H1, <- H2, <- H3, H4.
repeat split; auto.
unfold Included.
intros.
inversion H7; auto.
generalize Marks_include.
intros.
unfold Included in H12.
apply (H12 _ _ (marker m1) Unmarked _).
tauto.
Qed.
Definition frees_invariant {A : Type} (m : Mem A) :=
Disjoint A (frees m) (Closures (pointer m) (roots m)).
Definition marks_all {A : Type} (m : Mem A) :=
Disjoint A (Marks A (marker m) Unmarked (nodes m)) (Closures (pointer m) (roots m)).
Lemma sweeper_frees : forall A (m1 m2 : Mem A),
frees_invariant m1 -> marks_all m1 -> Sweeper m1 m2 -> frees_invariant m2.
Proof.
unfold frees_invariant, marks_all, Sweeper.
intros.
decompose [and] H1.
rewrite <- H2, <- H3, H5.
apply Disjoint_intro; intros.
inversion H.
inversion H0.
specialize (H6 x).
specialize (H8 x).
intro.
inversion H9.
inversion H10.
apply H6.
apply Intersection_intro; auto.
apply H8.
apply Intersection_intro; auto.
Qed.
-Lemma disjoint_include: forall A (B C D : Ensemble A),
+Lemma disjoint_include: forall A (B C D : set A),
Disjoint A B C -> Included D C -> Disjoint A B D.
Proof.
intros.
inversion H.
apply Disjoint_intro; intros.
intro.
apply (H1 x).
inversion H2.
apply Intersection_intro; auto.
Qed.
Lemma marker_frees : forall A (m1 m2 : Mem A),
frees_invariant m1 -> Marker m1 m2 -> frees_invariant m2 /\ marks_all m2.
Proof.
unfold frees_invariant, Marker, marks_all.
split; intros.
decompose [and] H0.
rewrite <- H1, <- H2, <- H4.
tauto.
decompose [and] H0.
apply (disjoint_include _ _ (Marks A (marker m2) Marked (nodes m2))); auto.
apply Disjoint_intro.
intros.
intro.
inversion H5.
inversion H7.
inversion H8.
rewrite H11 in H14.
inversion H14.
Qed.
Definition GC {A : Type} (m1 m2 : Mem A) := exists m : Mem A,
Marker m1 m /\ Sweeper m m2.
Theorem gc_invariant : forall A (m1 m2 : Mem A),
invariant m1 -> GC m1 m2 -> invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0.
apply marker_invariant in H2.
apply sweeper_invariant in H3.
tauto.
tauto.
tauto.
Qed.
Theorem gc_free: forall A (m1 m2 : Mem A),
frees_invariant m1 -> GC m1 m2 -> frees_invariant m2.
Proof.
unfold GC.
intros.
decompose [ex and] H0.
apply marker_frees in H2.
decompose [and] H2.
apply sweeper_frees in H3.
tauto.
tauto.
tauto.
tauto.
Qed.
|
redhotpenguin/Class-Factory | 334e4f3ff9f04b6493e924517d635619e51151c8 | added t/MyFlexibleBand.pm | diff --git a/MANIFEST b/MANIFEST
index d8b2873..4c6ddbf 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,11 +1,12 @@
Changes
Makefile.PL
MANIFEST
README
lib/Class/Factory.pm
t/factory.t
t/MyCountryBand.pm
t/MyRockBand.pm
t/MySimpleBand.pm
+t/MyFlexibleBand.pm
META.yml Module meta-data (added by MakeMaker)
|
redhotpenguin/Class-Factory | 6401a1492cfc94c5dd87395670c2baa83749d038 | added get_factory_type_for() | diff --git a/Changes b/Changes
index 8a6d9ff..f861523 100644
--- a/Changes
+++ b/Changes
@@ -1,91 +1,91 @@
Revision history for Perl extension Class::Factory.
1.06 Tue Nov 6 21:16:07 CET 2007
- - Added remove_factory_type() and unregister_factory_type(). Marcel
- Gruenauer <[email protected]>
+ - Added remove_factory_type(), unregister_factory_type() and
+ get_factory_type_for(). Marcel Gruenauer <[email protected]>
1.05 Thu Feb 1 22:57:21 PST 2007
- Added method get_registered_class(), suggested by
Sebastian Knapp <[email protected]>
1.04 Mon Aug 20 22:26:15 PST 2006
- New maintainer, Fred Moyer <[email protected]>
- Add Devel::Cover support, current coverage is 71%
- Moved check for Test::More to MY::test
1.03 Thu Oct 14 10:08:08 EDT 2004
- Added 'get_my_factory()' and 'get_my_factory_type()' at
suggestion from Srdjan Jankovic.
1.02 Tue Oct 12 21:02:04 EDT 2004
- Ensure that new() returns undef if get_factory_class() doesn't
work properly and factory_error() is overridden (and the
overridden method doesn't die)
- Relatively minor documentation clarifications and additions
spurred by a Perlmonks post:
http://www.perlmonks.org/index.pl?node_id=398257
- Added a few more tests to ensure factory_log() and
factory_error() working properly
1.01 (never released for some reason)
- add_factory_type() checks %INC to see if a class is already
loaded. This gets rid of any 'Subroutine foo redefined' messages
you might see if warnings are turned on.
- All log/error messages now have variables in apostrophes
rather than brackes. So:
"Class [$class] not found"
becomes:
"Class '$class' not found"
It's just cleaner that way.
1.00 Mon Oct 7 11:15:50 EDT 2002
- Add overridable logging/errors (Thanks to Eric Andreychek
<[email protected]>)
- Subclasses do not need to implement any methods any longer --
using the module is a simple 'use base qw( Class::Factory )'
away. (Thanks to Eric for the suggestion.)
- Add get_loaded_types(), get_loaded_classes(),
get_registered_types() and get_registered_classes() so you can
keep track of the factory state.
0.03 Sun Feb 10 13:00:20 EST 2002
Added the ability to register a type/class without having
Class::Factory include it. This is useful for modules that want
to know all of their types at startup time but don't want to
bring in a particular class until that type is requested. (See
POD for details.)
0.02 Wed Jan 30 00:22:58 EST 2002
Added simple constructor to be inherited as needed. This
constructor automatically calls 'init()', not coincidentally the
name that Class::Base uses. Small variable name changes.
0.01 Mon Jan 28 08:35:09 EST 2002
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
diff --git a/META.yml b/META.yml
index d6b8e0b..30c0b57 100644
--- a/META.yml
+++ b/META.yml
@@ -1,10 +1,10 @@
# http://module-build.sourceforge.net/META-spec.html
#XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX#
name: Class-Factory
-version: 1.05
+version: 1.06
version_from: lib/Class/Factory.pm
installdirs: site
requires:
distribution_type: module
generated_by: ExtUtils::MakeMaker version 6.17
diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 87ecf0c..8b9f042 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,785 +1,798 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '1.05';
+$Class::Factory::VERSION = '1.06';
my %CLASS_BY_FACTORY_AND_TYPE = ();
my %FACTORY_INFO_BY_CLASS = ();
my %REGISTER = ();
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $factory_class =
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
return $factory_class if ( $factory_class );
$factory_class = $REGISTER{ $class }->{ $object_type };
if ( $factory_class ) {
my $added_class =
$class->add_factory_type( $object_type, $factory_class );
return $added_class;
}
$item->factory_error( "Factory type '$object_type' is not defined ",
"in '$class'" );
return undef;
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no ",
"type defined");
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class =
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to add type '$object_type' to '$class' ",
"redundant; type already exists with class ",
"'$set_object_class'" );
return;
}
# Make sure the object class looks like a perl module/script
# Acceptable formats:
# Module.pm Module.ph Module.pl Module
$object_class =~ m/^([\w:-]+(?:\.(?:pm|ph|pl))?)$/;
$object_class = $1;
if ( $INC{ $object_class } ) {
$item->factory_log( "Looks like class '$object_class' was already ",
"included; no further work necessary" );
}
else {
eval "require $object_class";
if ( $@ ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"class '$class': factory class '$object_class' ",
"cannot be required: $@" );
return undef;
}
}
# keep track of what classes have been included so far...
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type } = $object_class;
# keep track of what factory and type are associated with a loaded
# class...
$FACTORY_INFO_BY_CLASS{ $object_class } = [ $class, $object_type ];
return $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no type ",
"defined" );
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class = $REGISTER{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to register type '$object_type' with ",
"'$class' is redundant; type registered with ",
"class '$set_object_class'" );
return;
}
return $REGISTER{ $class }->{ $object_type } = $object_class;
}
sub remove_factory_type {
my ( $item, @object_types ) = @_;
my $class = ref $item || $item;
for my $object_type (@object_types) {
unless ( $object_type ) {
$item->factory_error(
"Cannot remove factory type from '$class': no type defined"
);
}
delete $CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
}
}
sub unregister_factory_type {
my ( $item, @object_types ) = @_;
my $class = ref $item || $item;
for my $object_type (@object_types) {
unless ( $object_type ) {
$item->factory_error(
"Cannot remove factory type from '$class': no type defined"
);
}
delete $REGISTER{ $class }->{ $object_type };
# Also delete from $CLASS_BY_FACTORY_AND_TYPE because if the object
# type has already been instantiated, then it will have been processed
# by add_factory_type(), thus creating an entry in
# $CLASS_BY_FACTORY_AND_TYPE. We can call register_factory_type()
# again, but when we try to instantiate an object via
# get_factory_class(), it will find the old entry in
# $CLASS_BY_FACTORY_AND_TYPE and use that.
delete $CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
}
}
sub get_loaded_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
return sort values %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_loaded_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
return sort keys %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_registered_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort values %{ $REGISTER{ $class } };
}
sub get_registered_class {
my ( $item, $type ) = @_;
unless ( $type ) {
warn("No factory type passed");
return undef;
}
my $class = ref $item || $item;
return undef unless ( ref $REGISTER{ $class } eq 'HASH' );
return $REGISTER{ $class }{ $type };
}
sub get_registered_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort keys %{ $REGISTER{ $class } };
}
# Return the factory class that created $item (which can be an object
# or class)
sub get_my_factory {
my ( $item ) = @_;
my $impl_class = ref( $item ) || $item;
my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
if ( ref( $impl_info ) eq 'ARRAY' ) {
return $impl_info->[0];
}
return undef;
}
# Return the type that the factory used to create $item (which can be
# an object or class)
sub get_my_factory_type {
my ( $item ) = @_;
+ $item->get_factory_type_for($item);
+}
+
+
+# Return the type that the factory uses to create a given object or class.
+
+sub get_factory_type_for {
+ my ( $self, $item ) = @_;
my $impl_class = ref( $item ) || $item;
my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
if ( ref( $impl_info ) eq 'ARRAY' ) {
return $impl_info->[1];
}
return undef;
}
########################################
# Overridable Log / Error
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
# Add our default types
# This type is loaded when the statement is run
__PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
__PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
# brought in via 'require' immediately
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
# Registering a new factory type in code; 'Other::Custom::ClassTwo'
# isn't brought in yet...
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
# ...it's only 'require'd when the first instance of the type is
# created
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
# Get all the loaded and registered classes and types
my @loaded_classes = My::Factory->get_loaded_classes;
my @loaded_types = My::Factory->get_loaded_types;
my @registered_classes = My::Factory->get_registered_classes;
my @registered_types = My::Factory->get_registered_types;
# Get a registered class by it's factory type
my $registered_class = My::Factory->get_registered_class( 'type' );
# Ask the object created by the factory: Where did I come from?
my $custom_object = My::Factory->new( 'custom' );
print "Object was created by factory: ",
$custom_object->get_my_factory, " ",
"and is of type: ",
$custom_object->get_my_factory_type;
# Remove a factory type
My::Factory->remove_factory_type('perl');
# Unregister a factory type
My::Factory->unregister_factory_type('blech');
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. Configuration files are a good example of
this. There are four basic operations you would want to do with any
configuration: read the file in, lookup a value, set a value, write
the file out. There are also many different types of configuration
files, and you may want users to be able to provide an implementation
for their own home-grown configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you. Here's a sample interface and our two built-in
configuration types:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->add_factory_type( ini => 'My::IniReader' );
__PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
# Now register my type with the factory
My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
1;
(You may not wish to make your factory the same as your interface, but
this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
use My::CustomConfig; # this adds the factory type 'custom'...
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
print "Configuration is a: ", ref( $config ), "\n";
Which prints:
Configuration is a My::CustomConfig
And they can even add their own:
My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
This might not seem like a very big win, and for small standalone
applications probably isn't. But when you develop large applications
the C<(add|register)_factory_type()> step will almost certainly be
done at application initialization time, hidden away from the eyes of
the application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above implementation for subclasses is very
simple -- just add C<Class::Factory> to your inheritance tree and you
are done.
=head2 Gotchas
All type-to-class mapping information is stored under the original
subclass name. So the following will not do what you expect:
package My::Factory;
use base qw( Class::Factory );
...
package My::Implementation;
use base qw( My::Factory );
...
My::Implementation->register_factory_type( impl => 'My::Implementation' );
This does not register 'My::Implementation' under 'My::Factory' as you
would like, it registers the type under 'My::Implementation' because
that's the class we used to invoke the 'register_factory_type'
method. Make all C<add_factory_type()> and C<register_factory_type()>
invocations with the original factory class name and you'll be golden.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
parses GET/POST parameters. One type uses the ubiquitous L<CGI|CGI>
module, the other uses the faster but rarer
L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
that type is requested will we bring that implementation in. To extend
our configuration example above we'll change the configuration factory
to use C<register_factory_type()> instead of C<add_factory_type()>:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->register_factory_type( ini => 'My::IniReader' );
__PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
1;
This way you can leave the actual inclusion of the module for people
who would actually use it. For our configuration example we might
have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
=head2 Subclassing
Piece of cake:
package My::Factory;
use base qw( Class::Factory );
or the old-school:
package My::Factory;
use Class::Factory;
@My::Factory::ISA = qw( Class::Factory );
You can also override two methods for logging/error handling. There
are a few instances where C<Class::Factory> may generate a warning
message, or even a fatal error. Internally, these are handled using
C<warn> and C<die>, respectively.
This may not always be what you want though. Maybe you have a
different logging facility you wish to use. Perhaps you have a more
sophisticated method of handling errors (like
L<Log::Log4perl|Log::Log4perl>. If this is the case, you are welcome
to override either of these methods.
Currently, these two methods are implemented like the following:
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
Assume that instead of using C<warn>, you wish to use
L<Log::Log4perl|Log::Log4perl>. So, in your subclass, you might
override C<factory_log> like so:
sub factory_log {
shift;
my $logger = get_logger;
$logger->warn( @_ );
}
=head2 Common Usage Pattern: Initializing from the constructor
This is a very common pattern: Subclasses create an C<init()> method
that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
1;
And here is what a subclass might look like -- note that it doesn't
have to subclass C<My::Factory> as our earlier examples did:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
=head2 Registering Common Types by Default
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
use strict;
use base qw( Class::Factory );
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type2' );
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
use My::Factory;
my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );
=head1 METHODS
=head2 Factory Methods
B<new( $type, @params )>
This is a default constructor you can use. It is quite simple:
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
We just create a new object as a blessed hashref of the class
associated (from an earlier call to C<add_factory_type()> or
C<register_factory_type()>) with C<$type> and then call the C<init()>
method of that object. The C<init()> method should return the object,
or die on error.
If we do not get a class name from C<get_factory_class()> we issue a
C<factory_error()> message which typically means we throw a
C<die>. However, if you've overridden C<factory_error()> and do not
die, this factory call will return C<undef>.
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>. If C<$object_type> is
associated with a class and that class has already been included, the
class is returned. If C<$object_type> is registered with a class (not
yet included), then we try to C<require> the class. Any errors on the
C<require> bubble up to the caller. If there are no errors, the class
is returned.
Returns: name of class. If a class matching C<$object_type> is not
found or cannot be C<require>d, then a C<die()> (or more specifically,
a C<factory_error()>) is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then we
call C<factory_error()>. A C<factory_log()> message is issued if the
type has already been added.
B<register_factory_type( $object_type, $object_class )>
Tells the factory to register a new factory type. This type will be
dynamically included (using C<add_factory_type()> at the first request
for an instance of that type.
Returns: name of class registered if successful. If the proper
parameters are not given then we call C<factory_error()>. A
C<factory_log()> message is issued if the type has already been
registered.
B<remove_factory_type( @object_types )>
Removes a factory type from the factory. This is the opposite of
C<add_factory_type()>. No return value.
Removing a factory type is useful if a subclass of the factory wants to
redefine the mapping for the factory type. C<add_factory_type()> doesn't allow
overriding a factory type, so you have to remove it first.
B<unregister_factory_type( @object_types )>
Unregisters a factory type from the factory. This is the opposite of
C<register_factory_type()>. No return value.
Unregistering a factory type is useful if a subclass of the factory wants to
redefine the mapping for the factory type. C<register_factory_type()> doesn't
allow overriding a factory type, so you have to unregister it first.
+B<get_factory_type_for( $class )>
+
+Takes an object or a class name string and returns the factory type that is
+used to construct that class. Returns undef if there is no such factory type.
+
B<get_loaded_classes()>
Returns a sorted list of the currently loaded classes. If no classes
have been loaded yet, returns an empty list.
B<get_loaded_types()>
Returns a sorted list of the currently loaded types. If no classes
have been loaded yet, returns an empty list.
B<get_registered_classes()>
Returns a sorted list of the classes that were ever registered. If no
classes have been registered yet, returns an empty list.
Note that a class can be both registered and loaded since we do not
clear out the registration once a registered class has been loaded on
demand.
B<get_registered_class( $factory_type )>
Returns a registered class given a factory type.
If no class of type $factory_type is registered, returns undef.
If no classes have been registered yet, returns undef.
B<get_registered_types()>
Returns a sorted list of the types that were ever registered. If no
types have been registered yet, returns an empty list.
Note that a type can be both registered and loaded since we do not
clear out the registration once a registered type has been loaded on
demand.
B<factory_log( @message )>
Used internally instead of C<warn> so subclasses can override. Default
implementation just uses C<warn>.
B<factory_error( @message )>
Used internally instead of C<die> so subclasses can override. Default
implementation just uses C<die>.
=head2 Implementation Methods
If your implementations -- objects the factory creates -- also inherit
from the factory they can do a little introspection and tell you where
they came from. (Inheriting from the factory is a common usage: the
L<SYNOPSIS> example does it.)
All methods here can be called on either a class or an object.
B<get_my_factory()>
Returns the factory class used to create this object or instances of
this class. If this class (or object class) hasn't been registered
with the factory it returns undef.
So with our L<SYNOPSIS> example we could do:
my $custom_object = My::Factory->new( 'custom' );
print "Object was created by factory ",
"'", $custom_object->get_my_factory, "';
which would print:
Object was created by factory 'My::Factory'
B<get_my_factory_type()>
Returns the type used to by the factory create this object or
instances of this class. If this class (or object class) hasn't been
registered with the factory it returns undef.
So with our L<SYNOPSIS> example we could do:
my $custom_object = My::Factory->new( 'custom' );
print "Object is of type ",
"'", $custom_object->get_my_factory_type, "'";
which would print:
Object is of type 'custom'
=head1 COPYRIGHT
Copyright (c) 2002-2006 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHORS
Chris Winters E<lt>[email protected]<gt>
Eric Andreychek E<lt>[email protected]<gt> implemented overridable
log/error capability and prodded the module into a simpler design.
Srdjan Jankovic E<lt>[email protected]<gt> contributed the idea
for 'get_my_factory()' and 'get_my_factory_type()'
Sebastian Knapp <[email protected]> contributed the idea for
'get_registered_class()'
Marcel Gruenauer <[email protected]> contributed the methods
remove_factory_type() and unregister_factory_type().
diff --git a/t/factory.t b/t/factory.t
index 979d41d..7dcbc16 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,119 +1,126 @@
# -*-perl-*-
use strict;
-use Test::More tests => 36;
+use Test::More tests => 39;
use lib qw( ./t ./lib );
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
my @loaded_classes = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes, 1, 'Number of classes loaded so far' );
is( $loaded_classes[0], 'MyRockBand', 'Default class added' );
my @loaded_types = MySimpleBand->get_loaded_types;
is( scalar @loaded_types, 1, 'Number of types loaded so far' );
is( $loaded_types[0], 'rock', 'Default type added' );
my @registered_classes = MySimpleBand->get_registered_classes;
is( scalar @registered_classes, 1, 'Number of classes registered so far' );
is( $registered_classes[0], 'MyCountryBand', 'Default class registered' );
my @registered_types = MySimpleBand->get_registered_types;
is( scalar @registered_types, 1, 'Number of types registered so far' );
is( $registered_types[0], 'country', 'Default type registered' );
my $registered_class = MySimpleBand->get_registered_class( 'country' );
is( $registered_class, 'MyCountryBand', 'Get registered class from type');
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Type of added object returned' );
is( $rock->band_name(), $rock_band,
'Added object type super init parameter set' );
is( $rock->genre(), $rock_genre,
'Added object type self init parameter set' );
is( $rock->get_my_factory, 'MySimpleBand',
'Factory class retrievable from object' );
is( $rock->get_my_factory_type, 'rock',
'Factory type retrievable from object' );
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Type of registered object returned' );
is( $country->band_name(), $country_band,
'Registered object type super init parameter set' );
is( $country->genre(), $country_genre,
'Registered object type self init parameter set' );
is( $country->get_my_factory, 'MySimpleBand',
'Factory class retrievable from object' );
is( $country->get_my_factory_type, 'country',
'Factory type retrievable from object' );
my @loaded_classes_new = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes_new, 2, 'Classes loaded after all used' );
is( $loaded_classes_new[0], 'MyCountryBand', 'Default registered class now loaded' );
is( $loaded_classes_new[1], 'MyRockBand', 'Default added class still loaded' );
my @loaded_types_new = MySimpleBand->get_loaded_types;
is( scalar @loaded_types_new, 2, 'Types loaded after all used' );
is( $loaded_types_new[0], 'country', 'Default registered type now loaded' );
is( $loaded_types_new[1], 'rock', 'Default added type still loaded' );
is( MySimpleBand->get_factory_class( 'country' ), 'MyCountryBand',
'Proper class returned for registered type' );
is( MySimpleBand->get_factory_class( 'rock' ), 'MyRockBand',
'Proper class returned for added type' );
# reissue an add to get a warning
MySimpleBand->add_factory_type( rock => 'MyRockBand' );
is( $MySimpleBand::log_msg,
"Attempt to add type 'rock' to 'MySimpleBand' redundant; type already exists with class 'MyRockBand'",
'Generated correct log message with duplicate factory type added' );
# reissue a registration to get a warning
MySimpleBand->register_factory_type( country => 'MyCountryBand' );
is( $MySimpleBand::log_msg,
"Attempt to register type 'country' with 'MySimpleBand' is redundant; type registered with class 'MyCountryBand'",
'Generated correct log message with duplicate factory type registered' );
# generate an error message
MySimpleBand->add_factory_type( disco => 'SomeKeyboardGuy' );
ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
'Generated correct error message when adding nonexistent class' );
# generate an error message when creating an object of a nonexistent class
MySimpleBand->register_factory_type( disco => 'SomeKeyboardGuy' );
my $disco = MySimpleBand->new( 'disco', { shoes => 'white' } );
ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
'Generated correct error message when instantiate object with nonexistent class registration' );
MySimpleBand->unregister_factory_type('country');
MySimpleBand->new( 'country', { band_name => $country_band } );
ok( $MySimpleBand::error_msg =~ /^Factory type 'country' is not defined in 'MySimpleBand'/,
'Error message for instantiating after the factory type was unregistered' );
MySimpleBand->remove_factory_type('rock');
MySimpleBand->new( 'rock', { band_name => $rock_band } );
ok( $MySimpleBand::error_msg =~ /^Factory type 'rock' is not defined in 'MySimpleBand'/,
'Error message for instantiating after the factory type was removed' );
$MySimpleBand::log_msg = '';
MySimpleBand->add_factory_type( rock => 'MyRockBand' );
is( $MySimpleBand::log_msg, '', 'no warning after re-adding factory type');
+ is(MySimpleBand->get_factory_type_for('MyRockBand'), 'rock',
+ 'Factory type retrievable for any given class');
+ is(MySimpleBand->get_factory_type_for($rock), 'rock',
+ 'Factory type retrievable for any given object');
+
+ is(MySimpleBand->get_factory_type_for('MyJPopBand'), undef,
+ 'Factory type undef for unknown class');
}
|
redhotpenguin/Class-Factory | 68a7f203d87a5f1a543f42aab931f89a5ae4f35b | added implementation, documentation and tests for remove_factory_type() and unregister_factory_type() | diff --git a/Changes b/Changes
index 5059fc3..8a6d9ff 100644
--- a/Changes
+++ b/Changes
@@ -1,87 +1,91 @@
Revision history for Perl extension Class::Factory.
+1.06 Tue Nov 6 21:16:07 CET 2007
+ - Added remove_factory_type() and unregister_factory_type(). Marcel
+ Gruenauer <[email protected]>
+
1.05 Thu Feb 1 22:57:21 PST 2007
- Added method get_registered_class(), suggested by
Sebastian Knapp <[email protected]>
1.04 Mon Aug 20 22:26:15 PST 2006
- New maintainer, Fred Moyer <[email protected]>
- Add Devel::Cover support, current coverage is 71%
- Moved check for Test::More to MY::test
1.03 Thu Oct 14 10:08:08 EDT 2004
- Added 'get_my_factory()' and 'get_my_factory_type()' at
suggestion from Srdjan Jankovic.
1.02 Tue Oct 12 21:02:04 EDT 2004
- Ensure that new() returns undef if get_factory_class() doesn't
work properly and factory_error() is overridden (and the
overridden method doesn't die)
- Relatively minor documentation clarifications and additions
spurred by a Perlmonks post:
http://www.perlmonks.org/index.pl?node_id=398257
- Added a few more tests to ensure factory_log() and
factory_error() working properly
1.01 (never released for some reason)
- add_factory_type() checks %INC to see if a class is already
loaded. This gets rid of any 'Subroutine foo redefined' messages
you might see if warnings are turned on.
- All log/error messages now have variables in apostrophes
rather than brackes. So:
"Class [$class] not found"
becomes:
"Class '$class' not found"
It's just cleaner that way.
1.00 Mon Oct 7 11:15:50 EDT 2002
- Add overridable logging/errors (Thanks to Eric Andreychek
<[email protected]>)
- Subclasses do not need to implement any methods any longer --
using the module is a simple 'use base qw( Class::Factory )'
away. (Thanks to Eric for the suggestion.)
- Add get_loaded_types(), get_loaded_classes(),
get_registered_types() and get_registered_classes() so you can
keep track of the factory state.
0.03 Sun Feb 10 13:00:20 EST 2002
Added the ability to register a type/class without having
Class::Factory include it. This is useful for modules that want
to know all of their types at startup time but don't want to
bring in a particular class until that type is requested. (See
POD for details.)
0.02 Wed Jan 30 00:22:58 EST 2002
Added simple constructor to be inherited as needed. This
constructor automatically calls 'init()', not coincidentally the
name that Class::Base uses. Small variable name changes.
0.01 Mon Jan 28 08:35:09 EST 2002
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
diff --git a/README b/README
index 0332a16..d62b9c8 100644
--- a/README
+++ b/README
@@ -1,87 +1,99 @@
Class::Factory - Base class for dynamic factory classes
==========================
package My::Factory;
use strict;
use base qw( Class::Factory );
# Add our default types
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
# Register optional types
My::Factory->register_factory_type( java => 'My::Factory::Java' );
1;
# Create new objects using the default types
my $perl_item = My::Factory->new( 'perl', foo => 'bar' );
my $blech_item = My::Factory->new( 'blech', foo => 'baz' );
# Create new object using the optional type; this library is loaded
# on the first use
my $java_item = My::Factory->new( 'java', foo => 'quux' );
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', this => 'that' );
# Register a new factory type in code
My::Factory->register_factory_type( bleededge => 'Other::Customized::Class' );
my $edgy_object = My::Factory->new( 'bleededge', this => 'that' );
# Get a registered class name given it's factory type
my $registered_class = MyFactory->get_registered_class( 'bleededge' );
+ # Remove a factory type
+
+ MyFactory->remove_factory_type('custom');
+
+ # Unregister a factory type
+
+ MyFactory->unregister_factory_type('bleededge');
+
See POD for details
INSTALLATION
To install this module perform the typical four-part Perl salute:
perl Makefile.PL
make
make test
make install
DEPENDENCIES
None, although this module was written almost entirely under the
influence of Weezer.
get_registered_class() was written under the influence of Phix.
SIDE-EFFECTS
May include headache, insomnia, and growth spurts, although a control
group given English toffees in place had the same effects.
COPYRIGHT AND LICENCE
Copyright (c) 2002-2007 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
AUTHORS
Fred Moyer <[email protected]> is the current maintainer.
Chris Winters <[email protected]> is the author of Class::Factory.
Eric Andreychek <[email protected]> also helped out with code,
testing and good advice.
Srdjan Jankovic <[email protected]> contributed the idea for
'get_my_factory()' and 'get_my_factory_type()'
Sebastian Knapp <[email protected]> contributed the idea for
'get_registered_class()'
+
+Marcel Gruenauer <[email protected]> contributed the methods
+remove_factory_type() and unregister_factory_type().
+
diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 406aa53..87ecf0c 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,713 +1,785 @@
package Class::Factory;
# $Id$
use strict;
$Class::Factory::VERSION = '1.05';
my %CLASS_BY_FACTORY_AND_TYPE = ();
my %FACTORY_INFO_BY_CLASS = ();
my %REGISTER = ();
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $factory_class =
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
return $factory_class if ( $factory_class );
$factory_class = $REGISTER{ $class }->{ $object_type };
if ( $factory_class ) {
my $added_class =
$class->add_factory_type( $object_type, $factory_class );
return $added_class;
}
$item->factory_error( "Factory type '$object_type' is not defined ",
"in '$class'" );
return undef;
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no ",
"type defined");
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class =
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to add type '$object_type' to '$class' ",
"redundant; type already exists with class ",
"'$set_object_class'" );
return;
}
# Make sure the object class looks like a perl module/script
# Acceptable formats:
# Module.pm Module.ph Module.pl Module
$object_class =~ m/^([\w:-]+(?:\.(?:pm|ph|pl))?)$/;
$object_class = $1;
if ( $INC{ $object_class } ) {
$item->factory_log( "Looks like class '$object_class' was already ",
"included; no further work necessary" );
}
else {
eval "require $object_class";
if ( $@ ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"class '$class': factory class '$object_class' ",
"cannot be required: $@" );
return undef;
}
}
# keep track of what classes have been included so far...
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type } = $object_class;
# keep track of what factory and type are associated with a loaded
# class...
$FACTORY_INFO_BY_CLASS{ $object_class } = [ $class, $object_type ];
return $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no type ",
"defined" );
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class = $REGISTER{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to register type '$object_type' with ",
"'$class' is redundant; type registered with ",
"class '$set_object_class'" );
return;
}
return $REGISTER{ $class }->{ $object_type } = $object_class;
}
+sub remove_factory_type {
+ my ( $item, @object_types ) = @_;
+ my $class = ref $item || $item;
+
+ for my $object_type (@object_types) {
+ unless ( $object_type ) {
+ $item->factory_error(
+ "Cannot remove factory type from '$class': no type defined"
+ );
+ }
+
+ delete $CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
+ }
+}
+
+
+sub unregister_factory_type {
+ my ( $item, @object_types ) = @_;
+ my $class = ref $item || $item;
+
+ for my $object_type (@object_types) {
+ unless ( $object_type ) {
+ $item->factory_error(
+ "Cannot remove factory type from '$class': no type defined"
+ );
+ }
+
+ delete $REGISTER{ $class }->{ $object_type };
+
+ # Also delete from $CLASS_BY_FACTORY_AND_TYPE because if the object
+ # type has already been instantiated, then it will have been processed
+ # by add_factory_type(), thus creating an entry in
+ # $CLASS_BY_FACTORY_AND_TYPE. We can call register_factory_type()
+ # again, but when we try to instantiate an object via
+ # get_factory_class(), it will find the old entry in
+ # $CLASS_BY_FACTORY_AND_TYPE and use that.
+
+ delete $CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
+ }
+}
+
+
sub get_loaded_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
return sort values %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_loaded_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
return sort keys %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_registered_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort values %{ $REGISTER{ $class } };
}
sub get_registered_class {
my ( $item, $type ) = @_;
unless ( $type ) {
warn("No factory type passed");
return undef;
}
my $class = ref $item || $item;
return undef unless ( ref $REGISTER{ $class } eq 'HASH' );
return $REGISTER{ $class }{ $type };
}
sub get_registered_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort keys %{ $REGISTER{ $class } };
}
# Return the factory class that created $item (which can be an object
# or class)
sub get_my_factory {
my ( $item ) = @_;
my $impl_class = ref( $item ) || $item;
my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
if ( ref( $impl_info ) eq 'ARRAY' ) {
return $impl_info->[0];
}
return undef;
}
# Return the type that the factory used to create $item (which can be
# an object or class)
sub get_my_factory_type {
my ( $item ) = @_;
my $impl_class = ref( $item ) || $item;
my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
if ( ref( $impl_info ) eq 'ARRAY' ) {
return $impl_info->[1];
}
return undef;
}
########################################
# Overridable Log / Error
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
# Add our default types
# This type is loaded when the statement is run
__PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
__PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
# brought in via 'require' immediately
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
# Registering a new factory type in code; 'Other::Custom::ClassTwo'
# isn't brought in yet...
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
# ...it's only 'require'd when the first instance of the type is
# created
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
# Get all the loaded and registered classes and types
my @loaded_classes = My::Factory->get_loaded_classes;
my @loaded_types = My::Factory->get_loaded_types;
my @registered_classes = My::Factory->get_registered_classes;
my @registered_types = My::Factory->get_registered_types;
# Get a registered class by it's factory type
my $registered_class = My::Factory->get_registered_class( 'type' );
- # Ask the object created by the factory: Where did I come from?
+ # Ask the object created by the factory: Where did I come from?
- my $custom_object = My::Factory->new( 'custom' );
- print "Object was created by factory: ",
+ my $custom_object = My::Factory->new( 'custom' );
+ print "Object was created by factory: ",
$custom_object->get_my_factory, " ",
"and is of type: ",
$custom_object->get_my_factory_type;
+ # Remove a factory type
+
+ My::Factory->remove_factory_type('perl');
+
+ # Unregister a factory type
+
+ My::Factory->unregister_factory_type('blech');
+
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. Configuration files are a good example of
this. There are four basic operations you would want to do with any
configuration: read the file in, lookup a value, set a value, write
the file out. There are also many different types of configuration
files, and you may want users to be able to provide an implementation
for their own home-grown configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you. Here's a sample interface and our two built-in
configuration types:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->add_factory_type( ini => 'My::IniReader' );
__PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
# Now register my type with the factory
My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
1;
(You may not wish to make your factory the same as your interface, but
this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
use My::CustomConfig; # this adds the factory type 'custom'...
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
print "Configuration is a: ", ref( $config ), "\n";
Which prints:
Configuration is a My::CustomConfig
And they can even add their own:
My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
This might not seem like a very big win, and for small standalone
applications probably isn't. But when you develop large applications
the C<(add|register)_factory_type()> step will almost certainly be
done at application initialization time, hidden away from the eyes of
the application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above implementation for subclasses is very
simple -- just add C<Class::Factory> to your inheritance tree and you
are done.
=head2 Gotchas
All type-to-class mapping information is stored under the original
subclass name. So the following will not do what you expect:
package My::Factory;
use base qw( Class::Factory );
...
package My::Implementation;
use base qw( My::Factory );
...
My::Implementation->register_factory_type( impl => 'My::Implementation' );
This does not register 'My::Implementation' under 'My::Factory' as you
would like, it registers the type under 'My::Implementation' because
that's the class we used to invoke the 'register_factory_type'
method. Make all C<add_factory_type()> and C<register_factory_type()>
invocations with the original factory class name and you'll be golden.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
parses GET/POST parameters. One type uses the ubiquitous L<CGI|CGI>
module, the other uses the faster but rarer
L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
that type is requested will we bring that implementation in. To extend
our configuration example above we'll change the configuration factory
to use C<register_factory_type()> instead of C<add_factory_type()>:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->register_factory_type( ini => 'My::IniReader' );
__PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
1;
This way you can leave the actual inclusion of the module for people
who would actually use it. For our configuration example we might
have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
=head2 Subclassing
Piece of cake:
package My::Factory;
use base qw( Class::Factory );
or the old-school:
package My::Factory;
use Class::Factory;
@My::Factory::ISA = qw( Class::Factory );
You can also override two methods for logging/error handling. There
are a few instances where C<Class::Factory> may generate a warning
message, or even a fatal error. Internally, these are handled using
C<warn> and C<die>, respectively.
This may not always be what you want though. Maybe you have a
different logging facility you wish to use. Perhaps you have a more
sophisticated method of handling errors (like
L<Log::Log4perl|Log::Log4perl>. If this is the case, you are welcome
to override either of these methods.
Currently, these two methods are implemented like the following:
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
Assume that instead of using C<warn>, you wish to use
L<Log::Log4perl|Log::Log4perl>. So, in your subclass, you might
override C<factory_log> like so:
sub factory_log {
shift;
my $logger = get_logger;
$logger->warn( @_ );
}
=head2 Common Usage Pattern: Initializing from the constructor
This is a very common pattern: Subclasses create an C<init()> method
that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
1;
And here is what a subclass might look like -- note that it doesn't
have to subclass C<My::Factory> as our earlier examples did:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
=head2 Registering Common Types by Default
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
use strict;
use base qw( Class::Factory );
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type2' );
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
use My::Factory;
my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );
=head1 METHODS
=head2 Factory Methods
B<new( $type, @params )>
This is a default constructor you can use. It is quite simple:
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
We just create a new object as a blessed hashref of the class
associated (from an earlier call to C<add_factory_type()> or
C<register_factory_type()>) with C<$type> and then call the C<init()>
method of that object. The C<init()> method should return the object,
or die on error.
If we do not get a class name from C<get_factory_class()> we issue a
C<factory_error()> message which typically means we throw a
C<die>. However, if you've overridden C<factory_error()> and do not
die, this factory call will return C<undef>.
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>. If C<$object_type> is
associated with a class and that class has already been included, the
class is returned. If C<$object_type> is registered with a class (not
yet included), then we try to C<require> the class. Any errors on the
C<require> bubble up to the caller. If there are no errors, the class
is returned.
Returns: name of class. If a class matching C<$object_type> is not
found or cannot be C<require>d, then a C<die()> (or more specifically,
a C<factory_error()>) is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then we
call C<factory_error()>. A C<factory_log()> message is issued if the
type has already been added.
B<register_factory_type( $object_type, $object_class )>
Tells the factory to register a new factory type. This type will be
dynamically included (using C<add_factory_type()> at the first request
for an instance of that type.
Returns: name of class registered if successful. If the proper
parameters are not given then we call C<factory_error()>. A
C<factory_log()> message is issued if the type has already been
registered.
+B<remove_factory_type( @object_types )>
+
+Removes a factory type from the factory. This is the opposite of
+C<add_factory_type()>. No return value.
+
+Removing a factory type is useful if a subclass of the factory wants to
+redefine the mapping for the factory type. C<add_factory_type()> doesn't allow
+overriding a factory type, so you have to remove it first.
+
+B<unregister_factory_type( @object_types )>
+
+Unregisters a factory type from the factory. This is the opposite of
+C<register_factory_type()>. No return value.
+
+Unregistering a factory type is useful if a subclass of the factory wants to
+redefine the mapping for the factory type. C<register_factory_type()> doesn't
+allow overriding a factory type, so you have to unregister it first.
+
B<get_loaded_classes()>
Returns a sorted list of the currently loaded classes. If no classes
have been loaded yet, returns an empty list.
B<get_loaded_types()>
Returns a sorted list of the currently loaded types. If no classes
have been loaded yet, returns an empty list.
B<get_registered_classes()>
Returns a sorted list of the classes that were ever registered. If no
classes have been registered yet, returns an empty list.
Note that a class can be both registered and loaded since we do not
clear out the registration once a registered class has been loaded on
demand.
B<get_registered_class( $factory_type )>
Returns a registered class given a factory type.
If no class of type $factory_type is registered, returns undef.
If no classes have been registered yet, returns undef.
B<get_registered_types()>
Returns a sorted list of the types that were ever registered. If no
types have been registered yet, returns an empty list.
Note that a type can be both registered and loaded since we do not
clear out the registration once a registered type has been loaded on
demand.
B<factory_log( @message )>
Used internally instead of C<warn> so subclasses can override. Default
implementation just uses C<warn>.
B<factory_error( @message )>
Used internally instead of C<die> so subclasses can override. Default
implementation just uses C<die>.
=head2 Implementation Methods
If your implementations -- objects the factory creates -- also inherit
from the factory they can do a little introspection and tell you where
they came from. (Inheriting from the factory is a common usage: the
L<SYNOPSIS> example does it.)
All methods here can be called on either a class or an object.
B<get_my_factory()>
Returns the factory class used to create this object or instances of
this class. If this class (or object class) hasn't been registered
with the factory it returns undef.
So with our L<SYNOPSIS> example we could do:
my $custom_object = My::Factory->new( 'custom' );
print "Object was created by factory ",
"'", $custom_object->get_my_factory, "';
which would print:
Object was created by factory 'My::Factory'
B<get_my_factory_type()>
Returns the type used to by the factory create this object or
instances of this class. If this class (or object class) hasn't been
registered with the factory it returns undef.
So with our L<SYNOPSIS> example we could do:
my $custom_object = My::Factory->new( 'custom' );
print "Object is of type ",
"'", $custom_object->get_my_factory_type, "'";
which would print:
Object is of type 'custom'
=head1 COPYRIGHT
Copyright (c) 2002-2006 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHORS
Chris Winters E<lt>[email protected]<gt>
Eric Andreychek E<lt>[email protected]<gt> implemented overridable
log/error capability and prodded the module into a simpler design.
Srdjan Jankovic E<lt>[email protected]<gt> contributed the idea
for 'get_my_factory()' and 'get_my_factory_type()'
Sebastian Knapp <[email protected]> contributed the idea for
'get_registered_class()'
+
+Marcel Gruenauer <[email protected]> contributed the methods
+remove_factory_type() and unregister_factory_type().
+
diff --git a/t/factory.t b/t/factory.t
index c4cefe9..979d41d 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,105 +1,119 @@
# -*-perl-*-
use strict;
-use Test::More tests => 33;
+use Test::More tests => 36;
use lib qw( ./t ./lib );
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
my @loaded_classes = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes, 1, 'Number of classes loaded so far' );
is( $loaded_classes[0], 'MyRockBand', 'Default class added' );
my @loaded_types = MySimpleBand->get_loaded_types;
is( scalar @loaded_types, 1, 'Number of types loaded so far' );
is( $loaded_types[0], 'rock', 'Default type added' );
my @registered_classes = MySimpleBand->get_registered_classes;
is( scalar @registered_classes, 1, 'Number of classes registered so far' );
is( $registered_classes[0], 'MyCountryBand', 'Default class registered' );
my @registered_types = MySimpleBand->get_registered_types;
is( scalar @registered_types, 1, 'Number of types registered so far' );
is( $registered_types[0], 'country', 'Default type registered' );
my $registered_class = MySimpleBand->get_registered_class( 'country' );
is( $registered_class, 'MyCountryBand', 'Get registered class from type');
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Type of added object returned' );
is( $rock->band_name(), $rock_band,
'Added object type super init parameter set' );
is( $rock->genre(), $rock_genre,
'Added object type self init parameter set' );
is( $rock->get_my_factory, 'MySimpleBand',
'Factory class retrievable from object' );
is( $rock->get_my_factory_type, 'rock',
'Factory type retrievable from object' );
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Type of registered object returned' );
is( $country->band_name(), $country_band,
'Registered object type super init parameter set' );
is( $country->genre(), $country_genre,
'Registered object type self init parameter set' );
is( $country->get_my_factory, 'MySimpleBand',
'Factory class retrievable from object' );
is( $country->get_my_factory_type, 'country',
'Factory type retrievable from object' );
my @loaded_classes_new = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes_new, 2, 'Classes loaded after all used' );
is( $loaded_classes_new[0], 'MyCountryBand', 'Default registered class now loaded' );
is( $loaded_classes_new[1], 'MyRockBand', 'Default added class still loaded' );
my @loaded_types_new = MySimpleBand->get_loaded_types;
is( scalar @loaded_types_new, 2, 'Types loaded after all used' );
is( $loaded_types_new[0], 'country', 'Default registered type now loaded' );
is( $loaded_types_new[1], 'rock', 'Default added type still loaded' );
is( MySimpleBand->get_factory_class( 'country' ), 'MyCountryBand',
'Proper class returned for registered type' );
is( MySimpleBand->get_factory_class( 'rock' ), 'MyRockBand',
'Proper class returned for added type' );
# reissue an add to get a warning
MySimpleBand->add_factory_type( rock => 'MyRockBand' );
is( $MySimpleBand::log_msg,
"Attempt to add type 'rock' to 'MySimpleBand' redundant; type already exists with class 'MyRockBand'",
'Generated correct log message with duplicate factory type added' );
# reissue a registration to get a warning
MySimpleBand->register_factory_type( country => 'MyCountryBand' );
is( $MySimpleBand::log_msg,
"Attempt to register type 'country' with 'MySimpleBand' is redundant; type registered with class 'MyCountryBand'",
'Generated correct log message with duplicate factory type registered' );
# generate an error message
MySimpleBand->add_factory_type( disco => 'SomeKeyboardGuy' );
ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
'Generated correct error message when adding nonexistent class' );
# generate an error message when creating an object of a nonexistent class
MySimpleBand->register_factory_type( disco => 'SomeKeyboardGuy' );
my $disco = MySimpleBand->new( 'disco', { shoes => 'white' } );
ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
'Generated correct error message when instantiate object with nonexistent class registration' );
+ MySimpleBand->unregister_factory_type('country');
+ MySimpleBand->new( 'country', { band_name => $country_band } );
+ ok( $MySimpleBand::error_msg =~ /^Factory type 'country' is not defined in 'MySimpleBand'/,
+ 'Error message for instantiating after the factory type was unregistered' );
+
+ MySimpleBand->remove_factory_type('rock');
+ MySimpleBand->new( 'rock', { band_name => $rock_band } );
+ ok( $MySimpleBand::error_msg =~ /^Factory type 'rock' is not defined in 'MySimpleBand'/,
+ 'Error message for instantiating after the factory type was removed' );
+
+ $MySimpleBand::log_msg = '';
+ MySimpleBand->add_factory_type( rock => 'MyRockBand' );
+ is( $MySimpleBand::log_msg, '', 'no warning after re-adding factory type');
+
}
|
redhotpenguin/Class-Factory | 99c5b166c5321195fa99c01ebe2b818df34aafe9 | Add method get_registered_class() and release 1.05 | diff --git a/Changes b/Changes
index 3ab8f4b..5059fc3 100644
--- a/Changes
+++ b/Changes
@@ -1,82 +1,87 @@
Revision history for Perl extension Class::Factory.
-1.04 Tue Aug 1 22:26:15 PST 2006
+1.05 Thu Feb 1 22:57:21 PST 2007
+ - Added method get_registered_class(), suggested by
+ Sebastian Knapp <[email protected]>
+
+1.04 Mon Aug 20 22:26:15 PST 2006
- New maintainer, Fred Moyer <[email protected]>
- - Add Devel::Cover support, current coverage is 71%
+ - Add Devel::Cover support, current coverage is 71%
+ - Moved check for Test::More to MY::test
1.03 Thu Oct 14 10:08:08 EDT 2004
- Added 'get_my_factory()' and 'get_my_factory_type()' at
suggestion from Srdjan Jankovic.
1.02 Tue Oct 12 21:02:04 EDT 2004
- Ensure that new() returns undef if get_factory_class() doesn't
work properly and factory_error() is overridden (and the
overridden method doesn't die)
- Relatively minor documentation clarifications and additions
spurred by a Perlmonks post:
http://www.perlmonks.org/index.pl?node_id=398257
- Added a few more tests to ensure factory_log() and
factory_error() working properly
1.01 (never released for some reason)
- add_factory_type() checks %INC to see if a class is already
loaded. This gets rid of any 'Subroutine foo redefined' messages
you might see if warnings are turned on.
- All log/error messages now have variables in apostrophes
rather than brackes. So:
"Class [$class] not found"
becomes:
"Class '$class' not found"
It's just cleaner that way.
1.00 Mon Oct 7 11:15:50 EDT 2002
- Add overridable logging/errors (Thanks to Eric Andreychek
<[email protected]>)
- Subclasses do not need to implement any methods any longer --
using the module is a simple 'use base qw( Class::Factory )'
away. (Thanks to Eric for the suggestion.)
- Add get_loaded_types(), get_loaded_classes(),
get_registered_types() and get_registered_classes() so you can
keep track of the factory state.
0.03 Sun Feb 10 13:00:20 EST 2002
Added the ability to register a type/class without having
Class::Factory include it. This is useful for modules that want
to know all of their types at startup time but don't want to
bring in a particular class until that type is requested. (See
POD for details.)
0.02 Wed Jan 30 00:22:58 EST 2002
Added simple constructor to be inherited as needed. This
constructor automatically calls 'init()', not coincidentally the
name that Class::Base uses. Small variable name changes.
0.01 Mon Jan 28 08:35:09 EST 2002
-
+
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
diff --git a/META.yml b/META.yml
index 0b14c91..d6b8e0b 100644
--- a/META.yml
+++ b/META.yml
@@ -1,10 +1,10 @@
+# http://module-build.sourceforge.net/META-spec.html
#XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX#
name: Class-Factory
-version: 1.03
+version: 1.05
version_from: lib/Class/Factory.pm
installdirs: site
requires:
- Test::More: 0.4
distribution_type: module
-generated_by: ExtUtils::MakeMaker version 6.12
+generated_by: ExtUtils::MakeMaker version 6.17
diff --git a/README b/README
index fb50012..0332a16 100644
--- a/README
+++ b/README
@@ -1,78 +1,87 @@
Class::Factory - Base class for dynamic factory classes
==========================
package My::Factory;
use strict;
use base qw( Class::Factory );
# Add our default types
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
# Register optional types
My::Factory->register_factory_type( java => 'My::Factory::Java' );
1;
# Create new objects using the default types
my $perl_item = My::Factory->new( 'perl', foo => 'bar' );
my $blech_item = My::Factory->new( 'blech', foo => 'baz' );
# Create new object using the optional type; this library is loaded
# on the first use
my $java_item = My::Factory->new( 'java', foo => 'quux' );
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', this => 'that' );
# Register a new factory type in code
My::Factory->register_factory_type( bleededge => 'Other::Customized::Class' );
my $edgy_object = My::Factory->new( 'bleededge', this => 'that' );
+ # Get a registered class name given it's factory type
+
+ my $registered_class = MyFactory->get_registered_class( 'bleededge' );
+
See POD for details
INSTALLATION
To install this module perform the typical four-part Perl salute:
perl Makefile.PL
make
make test
make install
DEPENDENCIES
None, although this module was written almost entirely under the
influence of Weezer.
+get_registered_class() was written under the influence of Phix.
+
SIDE-EFFECTS
May include headache, insomnia, and growth spurts, although a control
group given English toffees in place had the same effects.
COPYRIGHT AND LICENCE
-Copyright (c) 2002-2006 Chris Winters. All rights reserved.
+Copyright (c) 2002-2007 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
AUTHORS
Fred Moyer <[email protected]> is the current maintainer.
Chris Winters <[email protected]> is the author of Class::Factory.
Eric Andreychek <[email protected]> also helped out with code,
testing and good advice.
Srdjan Jankovic <[email protected]> contributed the idea for
'get_my_factory()' and 'get_my_factory_type()'
+
+Sebastian Knapp <[email protected]> contributed the idea for
+'get_registered_class()'
diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 2788bc5..406aa53 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,689 +1,713 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '1.04';
+$Class::Factory::VERSION = '1.05';
my %CLASS_BY_FACTORY_AND_TYPE = ();
my %FACTORY_INFO_BY_CLASS = ();
my %REGISTER = ();
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $factory_class =
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
return $factory_class if ( $factory_class );
$factory_class = $REGISTER{ $class }->{ $object_type };
if ( $factory_class ) {
my $added_class =
$class->add_factory_type( $object_type, $factory_class );
return $added_class;
}
$item->factory_error( "Factory type '$object_type' is not defined ",
"in '$class'" );
return undef;
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no ",
"type defined");
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class =
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to add type '$object_type' to '$class' ",
"redundant; type already exists with class ",
"'$set_object_class'" );
return;
}
# Make sure the object class looks like a perl module/script
# Acceptable formats:
# Module.pm Module.ph Module.pl Module
$object_class =~ m/^([\w:-]+(?:\.(?:pm|ph|pl))?)$/;
$object_class = $1;
if ( $INC{ $object_class } ) {
$item->factory_log( "Looks like class '$object_class' was already ",
"included; no further work necessary" );
}
else {
eval "require $object_class";
if ( $@ ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"class '$class': factory class '$object_class' ",
"cannot be required: $@" );
return undef;
}
}
# keep track of what classes have been included so far...
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type } = $object_class;
# keep track of what factory and type are associated with a loaded
# class...
$FACTORY_INFO_BY_CLASS{ $object_class } = [ $class, $object_type ];
return $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no type ",
"defined" );
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class = $REGISTER{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to register type '$object_type' with ",
"'$class' is redundant; type registered with ",
"class '$set_object_class'" );
return;
}
return $REGISTER{ $class }->{ $object_type } = $object_class;
}
sub get_loaded_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
return sort values %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_loaded_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
return sort keys %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_registered_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort values %{ $REGISTER{ $class } };
}
+sub get_registered_class {
+ my ( $item, $type ) = @_;
+ unless ( $type ) {
+ warn("No factory type passed");
+ return undef;
+ }
+ my $class = ref $item || $item;
+ return undef unless ( ref $REGISTER{ $class } eq 'HASH' );
+ return $REGISTER{ $class }{ $type };
+}
+
sub get_registered_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort keys %{ $REGISTER{ $class } };
}
# Return the factory class that created $item (which can be an object
# or class)
sub get_my_factory {
my ( $item ) = @_;
my $impl_class = ref( $item ) || $item;
my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
if ( ref( $impl_info ) eq 'ARRAY' ) {
return $impl_info->[0];
}
return undef;
}
# Return the type that the factory used to create $item (which can be
# an object or class)
sub get_my_factory_type {
my ( $item ) = @_;
my $impl_class = ref( $item ) || $item;
my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
if ( ref( $impl_info ) eq 'ARRAY' ) {
return $impl_info->[1];
}
return undef;
}
########################################
# Overridable Log / Error
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
# Add our default types
# This type is loaded when the statement is run
__PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
__PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
# brought in via 'require' immediately
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
# Registering a new factory type in code; 'Other::Custom::ClassTwo'
# isn't brought in yet...
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
# ...it's only 'require'd when the first instance of the type is
# created
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
# Get all the loaded and registered classes and types
my @loaded_classes = My::Factory->get_loaded_classes;
my @loaded_types = My::Factory->get_loaded_types;
my @registered_classes = My::Factory->get_registered_classes;
my @registered_types = My::Factory->get_registered_types;
+ # Get a registered class by it's factory type
+
+ my $registered_class = My::Factory->get_registered_class( 'type' );
+
# Ask the object created by the factory: Where did I come from?
my $custom_object = My::Factory->new( 'custom' );
print "Object was created by factory: ",
$custom_object->get_my_factory, " ",
"and is of type: ",
$custom_object->get_my_factory_type;
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. Configuration files are a good example of
this. There are four basic operations you would want to do with any
configuration: read the file in, lookup a value, set a value, write
the file out. There are also many different types of configuration
files, and you may want users to be able to provide an implementation
for their own home-grown configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you. Here's a sample interface and our two built-in
configuration types:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->add_factory_type( ini => 'My::IniReader' );
__PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
# Now register my type with the factory
My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
1;
(You may not wish to make your factory the same as your interface, but
this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
use My::CustomConfig; # this adds the factory type 'custom'...
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
print "Configuration is a: ", ref( $config ), "\n";
Which prints:
Configuration is a My::CustomConfig
And they can even add their own:
My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
This might not seem like a very big win, and for small standalone
applications probably isn't. But when you develop large applications
the C<(add|register)_factory_type()> step will almost certainly be
done at application initialization time, hidden away from the eyes of
the application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above implementation for subclasses is very
simple -- just add C<Class::Factory> to your inheritance tree and you
are done.
=head2 Gotchas
All type-to-class mapping information is stored under the original
subclass name. So the following will not do what you expect:
package My::Factory;
use base qw( Class::Factory );
...
package My::Implementation;
use base qw( My::Factory );
...
My::Implementation->register_factory_type( impl => 'My::Implementation' );
This does not register 'My::Implementation' under 'My::Factory' as you
would like, it registers the type under 'My::Implementation' because
that's the class we used to invoke the 'register_factory_type'
method. Make all C<add_factory_type()> and C<register_factory_type()>
invocations with the original factory class name and you'll be golden.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
parses GET/POST parameters. One type uses the ubiquitous L<CGI|CGI>
module, the other uses the faster but rarer
L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
that type is requested will we bring that implementation in. To extend
our configuration example above we'll change the configuration factory
to use C<register_factory_type()> instead of C<add_factory_type()>:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->register_factory_type( ini => 'My::IniReader' );
__PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
1;
This way you can leave the actual inclusion of the module for people
who would actually use it. For our configuration example we might
have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
=head2 Subclassing
Piece of cake:
package My::Factory;
use base qw( Class::Factory );
or the old-school:
package My::Factory;
use Class::Factory;
@My::Factory::ISA = qw( Class::Factory );
You can also override two methods for logging/error handling. There
are a few instances where C<Class::Factory> may generate a warning
message, or even a fatal error. Internally, these are handled using
C<warn> and C<die>, respectively.
This may not always be what you want though. Maybe you have a
different logging facility you wish to use. Perhaps you have a more
sophisticated method of handling errors (like
L<Log::Log4perl|Log::Log4perl>. If this is the case, you are welcome
to override either of these methods.
Currently, these two methods are implemented like the following:
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
Assume that instead of using C<warn>, you wish to use
L<Log::Log4perl|Log::Log4perl>. So, in your subclass, you might
override C<factory_log> like so:
sub factory_log {
shift;
my $logger = get_logger;
$logger->warn( @_ );
}
=head2 Common Usage Pattern: Initializing from the constructor
This is a very common pattern: Subclasses create an C<init()> method
that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
1;
And here is what a subclass might look like -- note that it doesn't
have to subclass C<My::Factory> as our earlier examples did:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
=head2 Registering Common Types by Default
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
use strict;
use base qw( Class::Factory );
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type2' );
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
use My::Factory;
my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );
=head1 METHODS
=head2 Factory Methods
B<new( $type, @params )>
This is a default constructor you can use. It is quite simple:
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
We just create a new object as a blessed hashref of the class
associated (from an earlier call to C<add_factory_type()> or
C<register_factory_type()>) with C<$type> and then call the C<init()>
method of that object. The C<init()> method should return the object,
or die on error.
If we do not get a class name from C<get_factory_class()> we issue a
C<factory_error()> message which typically means we throw a
C<die>. However, if you've overridden C<factory_error()> and do not
die, this factory call will return C<undef>.
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>. If C<$object_type> is
associated with a class and that class has already been included, the
class is returned. If C<$object_type> is registered with a class (not
yet included), then we try to C<require> the class. Any errors on the
C<require> bubble up to the caller. If there are no errors, the class
is returned.
Returns: name of class. If a class matching C<$object_type> is not
found or cannot be C<require>d, then a C<die()> (or more specifically,
a C<factory_error()>) is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then we
call C<factory_error()>. A C<factory_log()> message is issued if the
type has already been added.
B<register_factory_type( $object_type, $object_class )>
Tells the factory to register a new factory type. This type will be
dynamically included (using C<add_factory_type()> at the first request
for an instance of that type.
Returns: name of class registered if successful. If the proper
parameters are not given then we call C<factory_error()>. A
C<factory_log()> message is issued if the type has already been
registered.
B<get_loaded_classes()>
Returns a sorted list of the currently loaded classes. If no classes
have been loaded yet, returns an empty list.
B<get_loaded_types()>
Returns a sorted list of the currently loaded types. If no classes
have been loaded yet, returns an empty list.
B<get_registered_classes()>
Returns a sorted list of the classes that were ever registered. If no
classes have been registered yet, returns an empty list.
Note that a class can be both registered and loaded since we do not
clear out the registration once a registered class has been loaded on
demand.
+B<get_registered_class( $factory_type )>
+
+Returns a registered class given a factory type.
+If no class of type $factory_type is registered, returns undef.
+If no classes have been registered yet, returns undef.
+
B<get_registered_types()>
Returns a sorted list of the types that were ever registered. If no
types have been registered yet, returns an empty list.
Note that a type can be both registered and loaded since we do not
clear out the registration once a registered type has been loaded on
demand.
B<factory_log( @message )>
Used internally instead of C<warn> so subclasses can override. Default
implementation just uses C<warn>.
B<factory_error( @message )>
Used internally instead of C<die> so subclasses can override. Default
implementation just uses C<die>.
=head2 Implementation Methods
If your implementations -- objects the factory creates -- also inherit
from the factory they can do a little introspection and tell you where
they came from. (Inheriting from the factory is a common usage: the
L<SYNOPSIS> example does it.)
All methods here can be called on either a class or an object.
B<get_my_factory()>
Returns the factory class used to create this object or instances of
this class. If this class (or object class) hasn't been registered
with the factory it returns undef.
So with our L<SYNOPSIS> example we could do:
my $custom_object = My::Factory->new( 'custom' );
print "Object was created by factory ",
"'", $custom_object->get_my_factory, "';
which would print:
Object was created by factory 'My::Factory'
B<get_my_factory_type()>
Returns the type used to by the factory create this object or
instances of this class. If this class (or object class) hasn't been
registered with the factory it returns undef.
So with our L<SYNOPSIS> example we could do:
my $custom_object = My::Factory->new( 'custom' );
print "Object is of type ",
"'", $custom_object->get_my_factory_type, "'";
which would print:
Object is of type 'custom'
=head1 COPYRIGHT
-Copyright (c) 2002-2004 Chris Winters. All rights reserved.
+Copyright (c) 2002-2006 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHORS
Chris Winters E<lt>[email protected]<gt>
Eric Andreychek E<lt>[email protected]<gt> implemented overridable
log/error capability and prodded the module into a simpler design.
Srdjan Jankovic E<lt>[email protected]<gt> contributed the idea
for 'get_my_factory()' and 'get_my_factory_type()'
+
+Sebastian Knapp <[email protected]> contributed the idea for
+'get_registered_class()'
diff --git a/t/factory.t b/t/factory.t
index 5b69a47..c4cefe9 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,102 +1,105 @@
# -*-perl-*-
use strict;
-use Test::More tests => 32;
+use Test::More tests => 33;
use lib qw( ./t ./lib );
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
my @loaded_classes = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes, 1, 'Number of classes loaded so far' );
is( $loaded_classes[0], 'MyRockBand', 'Default class added' );
my @loaded_types = MySimpleBand->get_loaded_types;
is( scalar @loaded_types, 1, 'Number of types loaded so far' );
is( $loaded_types[0], 'rock', 'Default type added' );
my @registered_classes = MySimpleBand->get_registered_classes;
is( scalar @registered_classes, 1, 'Number of classes registered so far' );
is( $registered_classes[0], 'MyCountryBand', 'Default class registered' );
my @registered_types = MySimpleBand->get_registered_types;
is( scalar @registered_types, 1, 'Number of types registered so far' );
is( $registered_types[0], 'country', 'Default type registered' );
+
+ my $registered_class = MySimpleBand->get_registered_class( 'country' );
+ is( $registered_class, 'MyCountryBand', 'Get registered class from type');
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Type of added object returned' );
is( $rock->band_name(), $rock_band,
'Added object type super init parameter set' );
is( $rock->genre(), $rock_genre,
'Added object type self init parameter set' );
is( $rock->get_my_factory, 'MySimpleBand',
'Factory class retrievable from object' );
is( $rock->get_my_factory_type, 'rock',
'Factory type retrievable from object' );
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Type of registered object returned' );
is( $country->band_name(), $country_band,
'Registered object type super init parameter set' );
is( $country->genre(), $country_genre,
'Registered object type self init parameter set' );
is( $country->get_my_factory, 'MySimpleBand',
'Factory class retrievable from object' );
is( $country->get_my_factory_type, 'country',
'Factory type retrievable from object' );
my @loaded_classes_new = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes_new, 2, 'Classes loaded after all used' );
is( $loaded_classes_new[0], 'MyCountryBand', 'Default registered class now loaded' );
is( $loaded_classes_new[1], 'MyRockBand', 'Default added class still loaded' );
my @loaded_types_new = MySimpleBand->get_loaded_types;
is( scalar @loaded_types_new, 2, 'Types loaded after all used' );
is( $loaded_types_new[0], 'country', 'Default registered type now loaded' );
is( $loaded_types_new[1], 'rock', 'Default added type still loaded' );
is( MySimpleBand->get_factory_class( 'country' ), 'MyCountryBand',
'Proper class returned for registered type' );
is( MySimpleBand->get_factory_class( 'rock' ), 'MyRockBand',
'Proper class returned for added type' );
# reissue an add to get a warning
MySimpleBand->add_factory_type( rock => 'MyRockBand' );
is( $MySimpleBand::log_msg,
"Attempt to add type 'rock' to 'MySimpleBand' redundant; type already exists with class 'MyRockBand'",
'Generated correct log message with duplicate factory type added' );
# reissue a registration to get a warning
MySimpleBand->register_factory_type( country => 'MyCountryBand' );
is( $MySimpleBand::log_msg,
"Attempt to register type 'country' with 'MySimpleBand' is redundant; type registered with class 'MyCountryBand'",
'Generated correct log message with duplicate factory type registered' );
# generate an error message
MySimpleBand->add_factory_type( disco => 'SomeKeyboardGuy' );
ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
'Generated correct error message when adding nonexistent class' );
# generate an error message when creating an object of a nonexistent class
MySimpleBand->register_factory_type( disco => 'SomeKeyboardGuy' );
my $disco = MySimpleBand->new( 'disco', { shoes => 'white' } );
ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
'Generated correct error message when instantiate object with nonexistent class registration' );
}
|
redhotpenguin/Class-Factory | d889bcf68318840fae43adedc61e5c8dfce61347 | - Start 1.04 release - Add coverage support via Devel::Cover - Update Copyright | diff --git a/Changes b/Changes
index 1245fed..3ab8f4b 100644
--- a/Changes
+++ b/Changes
@@ -1,77 +1,82 @@
Revision history for Perl extension Class::Factory.
+1.04 Tue Aug 1 22:26:15 PST 2006
+
+ - New maintainer, Fred Moyer <[email protected]>
+ - Add Devel::Cover support, current coverage is 71%
+
1.03 Thu Oct 14 10:08:08 EDT 2004
- Added 'get_my_factory()' and 'get_my_factory_type()' at
suggestion from Srdjan Jankovic.
1.02 Tue Oct 12 21:02:04 EDT 2004
- Ensure that new() returns undef if get_factory_class() doesn't
work properly and factory_error() is overridden (and the
overridden method doesn't die)
- Relatively minor documentation clarifications and additions
spurred by a Perlmonks post:
http://www.perlmonks.org/index.pl?node_id=398257
- Added a few more tests to ensure factory_log() and
factory_error() working properly
1.01 (never released for some reason)
- add_factory_type() checks %INC to see if a class is already
loaded. This gets rid of any 'Subroutine foo redefined' messages
you might see if warnings are turned on.
- All log/error messages now have variables in apostrophes
rather than brackes. So:
"Class [$class] not found"
becomes:
"Class '$class' not found"
It's just cleaner that way.
1.00 Mon Oct 7 11:15:50 EDT 2002
- Add overridable logging/errors (Thanks to Eric Andreychek
<[email protected]>)
- Subclasses do not need to implement any methods any longer --
using the module is a simple 'use base qw( Class::Factory )'
away. (Thanks to Eric for the suggestion.)
- Add get_loaded_types(), get_loaded_classes(),
get_registered_types() and get_registered_classes() so you can
keep track of the factory state.
0.03 Sun Feb 10 13:00:20 EST 2002
Added the ability to register a type/class without having
Class::Factory include it. This is useful for modules that want
to know all of their types at startup time but don't want to
bring in a particular class until that type is requested. (See
POD for details.)
0.02 Wed Jan 30 00:22:58 EST 2002
Added simple constructor to be inherited as needed. This
constructor automatically calls 'init()', not coincidentally the
name that Class::Base uses. Small variable name changes.
0.01 Mon Jan 28 08:35:09 EST 2002
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
diff --git a/Makefile.PL b/Makefile.PL
index a9c1d1d..83f1f82 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,14 +1,35 @@
use ExtUtils::MakeMaker;
my %opts = (
'NAME' => 'Class::Factory',
'VERSION_FROM' => 'lib/Class/Factory.pm',
- 'PREREQ_PM' => { 'Test::More' => 0.40, }
);
if ( $ExtUtils::MakeMaker::VERSION >= 5.43 ) {
$opts{AUTHOR} = 'Chris Winters <[email protected]';
$opts{ABSTRACT} = 'Useful base class for factory classes',
}
WriteMakefile( %opts );
+
+sub MY::test {
+
+ my $test = shift->MM::test(@_);
+
+ eval { require Test::More } && ($Test::More::VERSION >= 0.62)
+or return <<EOF;
+test::
+\t\@echo sorry, cannot run tests without Test::More 0.62
+EOF
+
+ if ( eval { require Devel::Cover } ) {
+ $test .= <<EOF;
+testcover ::
+ cover -delete
+ HARNESS_PERL_SWITCHES=-MDevel::Cover make test
+ cover
+EOF
+ }
+
+ return $test;
+}
diff --git a/README b/README
index 1ec423c..fb50012 100644
--- a/README
+++ b/README
@@ -1,76 +1,78 @@
Class::Factory - Base class for dynamic factory classes
==========================
package My::Factory;
use strict;
use base qw( Class::Factory );
# Add our default types
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
# Register optional types
My::Factory->register_factory_type( java => 'My::Factory::Java' );
1;
# Create new objects using the default types
my $perl_item = My::Factory->new( 'perl', foo => 'bar' );
my $blech_item = My::Factory->new( 'blech', foo => 'baz' );
# Create new object using the optional type; this library is loaded
# on the first use
my $java_item = My::Factory->new( 'java', foo => 'quux' );
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', this => 'that' );
# Register a new factory type in code
My::Factory->register_factory_type( bleededge => 'Other::Customized::Class' );
my $edgy_object = My::Factory->new( 'bleededge', this => 'that' );
See POD for details
INSTALLATION
To install this module perform the typical four-part Perl salute:
perl Makefile.PL
make
make test
make install
DEPENDENCIES
None, although this module was written almost entirely under the
influence of Weezer.
SIDE-EFFECTS
May include headache, insomnia, and growth spurts, although a control
group given English toffees in place had the same effects.
COPYRIGHT AND LICENCE
-Copyright (c) 2002-2004 Chris Winters. All rights reserved.
+Copyright (c) 2002-2006 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
AUTHORS
-Chris Winters <[email protected]>
+Fred Moyer <[email protected]> is the current maintainer.
+
+Chris Winters <[email protected]> is the author of Class::Factory.
Eric Andreychek <[email protected]> also helped out with code,
testing and good advice.
Srdjan Jankovic <[email protected]> contributed the idea for
'get_my_factory()' and 'get_my_factory_type()'
diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 81799cb..2788bc5 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,519 +1,519 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '1.03';
+$Class::Factory::VERSION = '1.04';
my %CLASS_BY_FACTORY_AND_TYPE = ();
my %FACTORY_INFO_BY_CLASS = ();
my %REGISTER = ();
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $factory_class =
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
return $factory_class if ( $factory_class );
$factory_class = $REGISTER{ $class }->{ $object_type };
if ( $factory_class ) {
my $added_class =
$class->add_factory_type( $object_type, $factory_class );
return $added_class;
}
$item->factory_error( "Factory type '$object_type' is not defined ",
"in '$class'" );
return undef;
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no ",
"type defined");
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class =
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to add type '$object_type' to '$class' ",
"redundant; type already exists with class ",
"'$set_object_class'" );
return;
}
# Make sure the object class looks like a perl module/script
# Acceptable formats:
# Module.pm Module.ph Module.pl Module
$object_class =~ m/^([\w:-]+(?:\.(?:pm|ph|pl))?)$/;
$object_class = $1;
if ( $INC{ $object_class } ) {
$item->factory_log( "Looks like class '$object_class' was already ",
"included; no further work necessary" );
}
else {
eval "require $object_class";
if ( $@ ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"class '$class': factory class '$object_class' ",
"cannot be required: $@" );
return undef;
}
}
# keep track of what classes have been included so far...
$CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type } = $object_class;
# keep track of what factory and type are associated with a loaded
# class...
$FACTORY_INFO_BY_CLASS{ $object_class } = [ $class, $object_type ];
return $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no type ",
"defined" );
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class = $REGISTER{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to register type '$object_type' with ",
"'$class' is redundant; type registered with ",
"class '$set_object_class'" );
return;
}
return $REGISTER{ $class }->{ $object_type } = $object_class;
}
sub get_loaded_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
return sort values %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_loaded_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
return sort keys %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_registered_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort values %{ $REGISTER{ $class } };
}
sub get_registered_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort keys %{ $REGISTER{ $class } };
}
# Return the factory class that created $item (which can be an object
# or class)
sub get_my_factory {
my ( $item ) = @_;
my $impl_class = ref( $item ) || $item;
my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
if ( ref( $impl_info ) eq 'ARRAY' ) {
return $impl_info->[0];
}
return undef;
}
# Return the type that the factory used to create $item (which can be
# an object or class)
sub get_my_factory_type {
my ( $item ) = @_;
my $impl_class = ref( $item ) || $item;
my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
if ( ref( $impl_info ) eq 'ARRAY' ) {
return $impl_info->[1];
}
return undef;
}
########################################
# Overridable Log / Error
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
# Add our default types
# This type is loaded when the statement is run
__PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
__PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
# brought in via 'require' immediately
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
# Registering a new factory type in code; 'Other::Custom::ClassTwo'
# isn't brought in yet...
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
# ...it's only 'require'd when the first instance of the type is
# created
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
# Get all the loaded and registered classes and types
my @loaded_classes = My::Factory->get_loaded_classes;
my @loaded_types = My::Factory->get_loaded_types;
my @registered_classes = My::Factory->get_registered_classes;
my @registered_types = My::Factory->get_registered_types;
# Ask the object created by the factory: Where did I come from?
my $custom_object = My::Factory->new( 'custom' );
print "Object was created by factory: ",
$custom_object->get_my_factory, " ",
"and is of type: ",
$custom_object->get_my_factory_type;
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. Configuration files are a good example of
this. There are four basic operations you would want to do with any
configuration: read the file in, lookup a value, set a value, write
the file out. There are also many different types of configuration
files, and you may want users to be able to provide an implementation
for their own home-grown configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you. Here's a sample interface and our two built-in
configuration types:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->add_factory_type( ini => 'My::IniReader' );
__PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
# Now register my type with the factory
My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
1;
(You may not wish to make your factory the same as your interface, but
this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
use My::CustomConfig; # this adds the factory type 'custom'...
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
print "Configuration is a: ", ref( $config ), "\n";
Which prints:
Configuration is a My::CustomConfig
And they can even add their own:
My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
This might not seem like a very big win, and for small standalone
applications probably isn't. But when you develop large applications
the C<(add|register)_factory_type()> step will almost certainly be
done at application initialization time, hidden away from the eyes of
the application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above implementation for subclasses is very
simple -- just add C<Class::Factory> to your inheritance tree and you
are done.
=head2 Gotchas
All type-to-class mapping information is stored under the original
subclass name. So the following will not do what you expect:
package My::Factory;
use base qw( Class::Factory );
...
package My::Implementation;
use base qw( My::Factory );
...
My::Implementation->register_factory_type( impl => 'My::Implementation' );
This does not register 'My::Implementation' under 'My::Factory' as you
would like, it registers the type under 'My::Implementation' because
that's the class we used to invoke the 'register_factory_type'
method. Make all C<add_factory_type()> and C<register_factory_type()>
invocations with the original factory class name and you'll be golden.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
parses GET/POST parameters. One type uses the ubiquitous L<CGI|CGI>
module, the other uses the faster but rarer
L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
that type is requested will we bring that implementation in. To extend
our configuration example above we'll change the configuration factory
to use C<register_factory_type()> instead of C<add_factory_type()>:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->register_factory_type( ini => 'My::IniReader' );
__PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
1;
This way you can leave the actual inclusion of the module for people
who would actually use it. For our configuration example we might
have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
=head2 Subclassing
Piece of cake:
package My::Factory;
use base qw( Class::Factory );
or the old-school:
package My::Factory;
use Class::Factory;
@My::Factory::ISA = qw( Class::Factory );
You can also override two methods for logging/error handling. There
are a few instances where C<Class::Factory> may generate a warning
message, or even a fatal error. Internally, these are handled using
C<warn> and C<die>, respectively.
This may not always be what you want though. Maybe you have a
different logging facility you wish to use. Perhaps you have a more
sophisticated method of handling errors (like
L<Log::Log4perl|Log::Log4perl>. If this is the case, you are welcome
to override either of these methods.
Currently, these two methods are implemented like the following:
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
Assume that instead of using C<warn>, you wish to use
L<Log::Log4perl|Log::Log4perl>. So, in your subclass, you might
override C<factory_log> like so:
sub factory_log {
shift;
my $logger = get_logger;
$logger->warn( @_ );
}
=head2 Common Usage Pattern: Initializing from the constructor
This is a very common pattern: Subclasses create an C<init()> method
that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
1;
And here is what a subclass might look like -- note that it doesn't
have to subclass C<My::Factory> as our earlier examples did:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
=head2 Registering Common Types by Default
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
use strict;
use base qw( Class::Factory );
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type2' );
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
|
redhotpenguin/Class-Factory | 763f99cd85d1a8331d1cdfd185e3324a2b7bdda6 | 1.03: implement get_my_factory() and get_my_factory_type() at suggestion of Srdjan Jankovic | diff --git a/Changes b/Changes
index b12b9b3..1245fed 100644
--- a/Changes
+++ b/Changes
@@ -1,71 +1,77 @@
Revision history for Perl extension Class::Factory.
+1.03 Thu Oct 14 10:08:08 EDT 2004
+
+ - Added 'get_my_factory()' and 'get_my_factory_type()' at
+ suggestion from Srdjan Jankovic.
+
+
1.02 Tue Oct 12 21:02:04 EDT 2004
- Ensure that new() returns undef if get_factory_class() doesn't
work properly and factory_error() is overridden (and the
overridden method doesn't die)
- Relatively minor documentation clarifications and additions
spurred by a Perlmonks post:
http://www.perlmonks.org/index.pl?node_id=398257
- Added a few more tests to ensure factory_log() and
factory_error() working properly
1.01 (never released for some reason)
- add_factory_type() checks %INC to see if a class is already
loaded. This gets rid of any 'Subroutine foo redefined' messages
you might see if warnings are turned on.
- All log/error messages now have variables in apostrophes
rather than brackes. So:
"Class [$class] not found"
becomes:
"Class '$class' not found"
It's just cleaner that way.
1.00 Mon Oct 7 11:15:50 EDT 2002
- Add overridable logging/errors (Thanks to Eric Andreychek
<[email protected]>)
- Subclasses do not need to implement any methods any longer --
using the module is a simple 'use base qw( Class::Factory )'
away. (Thanks to Eric for the suggestion.)
- Add get_loaded_types(), get_loaded_classes(),
get_registered_types() and get_registered_classes() so you can
keep track of the factory state.
0.03 Sun Feb 10 13:00:20 EST 2002
Added the ability to register a type/class without having
Class::Factory include it. This is useful for modules that want
to know all of their types at startup time but don't want to
bring in a particular class until that type is requested. (See
POD for details.)
0.02 Wed Jan 30 00:22:58 EST 2002
Added simple constructor to be inherited as needed. This
constructor automatically calls 'init()', not coincidentally the
name that Class::Base uses. Small variable name changes.
0.01 Mon Jan 28 08:35:09 EST 2002
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
diff --git a/README b/README
index 1af56e2..1ec423c 100644
--- a/README
+++ b/README
@@ -1,73 +1,76 @@
Class::Factory - Base class for dynamic factory classes
==========================
package My::Factory;
use strict;
use base qw( Class::Factory );
# Add our default types
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
# Register optional types
My::Factory->register_factory_type( java => 'My::Factory::Java' );
1;
# Create new objects using the default types
my $perl_item = My::Factory->new( 'perl', foo => 'bar' );
my $blech_item = My::Factory->new( 'blech', foo => 'baz' );
# Create new object using the optional type; this library is loaded
# on the first use
my $java_item = My::Factory->new( 'java', foo => 'quux' );
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', this => 'that' );
# Register a new factory type in code
My::Factory->register_factory_type( bleededge => 'Other::Customized::Class' );
my $edgy_object = My::Factory->new( 'bleededge', this => 'that' );
See POD for details
INSTALLATION
To install this module perform the typical four-part Perl salute:
perl Makefile.PL
make
make test
make install
DEPENDENCIES
None, although this module was written almost entirely under the
influence of Weezer.
SIDE-EFFECTS
May include headache, insomnia, and growth spurts, although a control
group given English toffees in place had the same effects.
COPYRIGHT AND LICENCE
-Copyright (c) 2002 Chris Winters. All rights reserved.
+Copyright (c) 2002-2004 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
AUTHORS
Chris Winters <[email protected]>
- * Eric Andreychek <[email protected]> also helped out with code,
- testing and good advice.
+Eric Andreychek <[email protected]> also helped out with code,
+testing and good advice.
+
+Srdjan Jankovic <[email protected]> contributed the idea for
+'get_my_factory()' and 'get_my_factory_type()'
diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 15075de..81799cb 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,598 +1,689 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '1.02';
+$Class::Factory::VERSION = '1.03';
-my %INCLUDE = ();
-my %REGISTER = ();
+my %CLASS_BY_FACTORY_AND_TYPE = ();
+my %FACTORY_INFO_BY_CLASS = ();
+my %REGISTER = ();
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
- my $factory_class = $INCLUDE{ $class }->{ $object_type };
+ my $factory_class =
+ $CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
return $factory_class if ( $factory_class );
$factory_class = $REGISTER{ $class }->{ $object_type };
if ( $factory_class ) {
my $added_class =
$class->add_factory_type( $object_type, $factory_class );
return $added_class;
}
$item->factory_error( "Factory type '$object_type' is not defined ",
"in '$class'" );
return undef;
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no ",
"type defined");
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
- my $set_object_class = $INCLUDE{ $class }->{ $object_type };
+ my $set_object_class =
+ $CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to add type '$object_type' to '$class' ",
"redundant; type already exists with class ",
"'$set_object_class'" );
return;
}
# Make sure the object class looks like a perl module/script
# Acceptable formats:
# Module.pm Module.ph Module.pl Module
$object_class =~ m/^([\w:-]+(?:\.(?:pm|ph|pl))?)$/;
$object_class = $1;
if ( $INC{ $object_class } ) {
$item->factory_log( "Looks like class '$object_class' was already ",
"included; no further work necessary" );
}
else {
eval "require $object_class";
if ( $@ ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"class '$class': factory class '$object_class' ",
"cannot be required: $@" );
return undef;
}
}
- return $INCLUDE{ $class }->{ $object_type } = $object_class;
+
+ # keep track of what classes have been included so far...
+ $CLASS_BY_FACTORY_AND_TYPE{ $class }->{ $object_type } = $object_class;
+
+ # keep track of what factory and type are associated with a loaded
+ # class...
+ $FACTORY_INFO_BY_CLASS{ $object_class } = [ $class, $object_type ];
+
+ return $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no type ",
"defined" );
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class = $REGISTER{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to register type '$object_type' with ",
"'$class' is redundant; type registered with ",
"class '$set_object_class'" );
return;
}
return $REGISTER{ $class }->{ $object_type } = $object_class;
}
sub get_loaded_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
- return () unless ( ref $INCLUDE{ $class } eq 'HASH' );
- return sort values %{ $INCLUDE{ $class } };
+ return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
+ return sort values %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_loaded_types {
my ( $item ) = @_;
my $class = ref $item || $item;
- return () unless ( ref $INCLUDE{ $class } eq 'HASH' );
- return sort keys %{ $INCLUDE{ $class } };
+ return () unless ( ref $CLASS_BY_FACTORY_AND_TYPE{ $class } eq 'HASH' );
+ return sort keys %{ $CLASS_BY_FACTORY_AND_TYPE{ $class } };
}
sub get_registered_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort values %{ $REGISTER{ $class } };
}
sub get_registered_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort keys %{ $REGISTER{ $class } };
}
+# Return the factory class that created $item (which can be an object
+# or class)
+
+sub get_my_factory {
+ my ( $item ) = @_;
+ my $impl_class = ref( $item ) || $item;
+ my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
+ if ( ref( $impl_info ) eq 'ARRAY' ) {
+ return $impl_info->[0];
+ }
+ return undef;
+}
+
+# Return the type that the factory used to create $item (which can be
+# an object or class)
+
+sub get_my_factory_type {
+ my ( $item ) = @_;
+ my $impl_class = ref( $item ) || $item;
+ my $impl_info = $FACTORY_INFO_BY_CLASS{ $impl_class };
+ if ( ref( $impl_info ) eq 'ARRAY' ) {
+ return $impl_info->[1];
+ }
+ return undef;
+}
+
########################################
# Overridable Log / Error
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
# Add our default types
# This type is loaded when the statement is run
__PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
__PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
# brought in via 'require' immediately
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
# Registering a new factory type in code; 'Other::Custom::ClassTwo'
# isn't brought in yet...
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
# ...it's only 'require'd when the first instance of the type is
# created
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
# Get all the loaded and registered classes and types
my @loaded_classes = My::Factory->get_loaded_classes;
my @loaded_types = My::Factory->get_loaded_types;
my @registered_classes = My::Factory->get_registered_classes;
my @registered_types = My::Factory->get_registered_types;
+ # Ask the object created by the factory: Where did I come from?
+
+ my $custom_object = My::Factory->new( 'custom' );
+ print "Object was created by factory: ",
+ $custom_object->get_my_factory, " ",
+ "and is of type: ",
+ $custom_object->get_my_factory_type;
+
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. Configuration files are a good example of
this. There are four basic operations you would want to do with any
configuration: read the file in, lookup a value, set a value, write
the file out. There are also many different types of configuration
files, and you may want users to be able to provide an implementation
for their own home-grown configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you. Here's a sample interface and our two built-in
configuration types:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->add_factory_type( ini => 'My::IniReader' );
__PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
# Now register my type with the factory
My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
1;
(You may not wish to make your factory the same as your interface, but
this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
use My::CustomConfig; # this adds the factory type 'custom'...
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
print "Configuration is a: ", ref( $config ), "\n";
Which prints:
Configuration is a My::CustomConfig
And they can even add their own:
My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
This might not seem like a very big win, and for small standalone
applications probably isn't. But when you develop large applications
the C<(add|register)_factory_type()> step will almost certainly be
done at application initialization time, hidden away from the eyes of
the application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above implementation for subclasses is very
simple -- just add C<Class::Factory> to your inheritance tree and you
are done.
=head2 Gotchas
All type-to-class mapping information is stored under the original
subclass name. So the following will not do what you expect:
package My::Factory;
use base qw( Class::Factory );
...
package My::Implementation;
use base qw( My::Factory );
...
My::Implementation->register_factory_type( impl => 'My::Implementation' );
This does not register 'My::Implementation' under 'My::Factory' as you
would like, it registers the type under 'My::Implementation' because
that's the class we used to invoke the 'register_factory_type'
method. Make all C<add_factory_type()> and C<register_factory_type()>
invocations with the original factory class name and you'll be golden.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
parses GET/POST parameters. One type uses the ubiquitous L<CGI|CGI>
module, the other uses the faster but rarer
L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
that type is requested will we bring that implementation in. To extend
our configuration example above we'll change the configuration factory
to use C<register_factory_type()> instead of C<add_factory_type()>:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->register_factory_type( ini => 'My::IniReader' );
__PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
1;
This way you can leave the actual inclusion of the module for people
who would actually use it. For our configuration example we might
have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
=head2 Subclassing
Piece of cake:
package My::Factory;
use base qw( Class::Factory );
or the old-school:
package My::Factory;
use Class::Factory;
@My::Factory::ISA = qw( Class::Factory );
You can also override two methods for logging/error handling. There
are a few instances where C<Class::Factory> may generate a warning
message, or even a fatal error. Internally, these are handled using
C<warn> and C<die>, respectively.
This may not always be what you want though. Maybe you have a
different logging facility you wish to use. Perhaps you have a more
sophisticated method of handling errors (like
L<Log::Log4perl|Log::Log4perl>. If this is the case, you are welcome
to override either of these methods.
Currently, these two methods are implemented like the following:
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
Assume that instead of using C<warn>, you wish to use
L<Log::Log4perl|Log::Log4perl>. So, in your subclass, you might
override C<factory_log> like so:
sub factory_log {
shift;
my $logger = get_logger;
$logger->warn( @_ );
}
=head2 Common Usage Pattern: Initializing from the constructor
This is a very common pattern: Subclasses create an C<init()> method
that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
1;
And here is what a subclass might look like -- note that it doesn't
have to subclass C<My::Factory> as our earlier examples did:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
=head2 Registering Common Types by Default
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
use strict;
use base qw( Class::Factory );
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type2' );
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
use My::Factory;
my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );
=head1 METHODS
+=head2 Factory Methods
+
B<new( $type, @params )>
This is a default constructor you can use. It is quite simple:
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
We just create a new object as a blessed hashref of the class
associated (from an earlier call to C<add_factory_type()> or
C<register_factory_type()>) with C<$type> and then call the C<init()>
method of that object. The C<init()> method should return the object,
or die on error.
If we do not get a class name from C<get_factory_class()> we issue a
C<factory_error()> message which typically means we throw a
C<die>. However, if you've overridden C<factory_error()> and do not
die, this factory call will return C<undef>.
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>. If C<$object_type> is
associated with a class and that class has already been included, the
class is returned. If C<$object_type> is registered with a class (not
yet included), then we try to C<require> the class. Any errors on the
C<require> bubble up to the caller. If there are no errors, the class
is returned.
Returns: name of class. If a class matching C<$object_type> is not
found or cannot be C<require>d, then a C<die()> (or more specifically,
a C<factory_error()>) is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then we
call C<factory_error()>. A C<factory_log()> message is issued if the
type has already been added.
B<register_factory_type( $object_type, $object_class )>
Tells the factory to register a new factory type. This type will be
dynamically included (using C<add_factory_type()> at the first request
for an instance of that type.
Returns: name of class registered if successful. If the proper
parameters are not given then we call C<factory_error()>. A
C<factory_log()> message is issued if the type has already been
registered.
B<get_loaded_classes()>
Returns a sorted list of the currently loaded classes. If no classes
have been loaded yet, returns an empty list.
B<get_loaded_types()>
Returns a sorted list of the currently loaded types. If no classes
have been loaded yet, returns an empty list.
B<get_registered_classes()>
Returns a sorted list of the classes that were ever registered. If no
classes have been registered yet, returns an empty list.
Note that a class can be both registered and loaded since we do not
clear out the registration once a registered class has been loaded on
demand.
B<get_registered_types()>
Returns a sorted list of the types that were ever registered. If no
types have been registered yet, returns an empty list.
Note that a type can be both registered and loaded since we do not
clear out the registration once a registered type has been loaded on
demand.
B<factory_log( @message )>
Used internally instead of C<warn> so subclasses can override. Default
implementation just uses C<warn>.
B<factory_error( @message )>
Used internally instead of C<die> so subclasses can override. Default
implementation just uses C<die>.
+=head2 Implementation Methods
+
+If your implementations -- objects the factory creates -- also inherit
+from the factory they can do a little introspection and tell you where
+they came from. (Inheriting from the factory is a common usage: the
+L<SYNOPSIS> example does it.)
+
+All methods here can be called on either a class or an object.
+
+B<get_my_factory()>
+
+Returns the factory class used to create this object or instances of
+this class. If this class (or object class) hasn't been registered
+with the factory it returns undef.
+
+So with our L<SYNOPSIS> example we could do:
+
+ my $custom_object = My::Factory->new( 'custom' );
+ print "Object was created by factory ",
+ "'", $custom_object->get_my_factory, "';
+
+which would print:
+
+ Object was created by factory 'My::Factory'
+
+B<get_my_factory_type()>
+
+Returns the type used to by the factory create this object or
+instances of this class. If this class (or object class) hasn't been
+registered with the factory it returns undef.
+
+So with our L<SYNOPSIS> example we could do:
+
+ my $custom_object = My::Factory->new( 'custom' );
+ print "Object is of type ",
+ "'", $custom_object->get_my_factory_type, "'";
+
+which would print:
+
+ Object is of type 'custom'
+
=head1 COPYRIGHT
Copyright (c) 2002-2004 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHORS
Chris Winters E<lt>[email protected]<gt>
Eric Andreychek E<lt>[email protected]<gt> implemented overridable
log/error capability and prodded the module into a simpler design.
+
+Srdjan Jankovic E<lt>[email protected]<gt> contributed the idea
+for 'get_my_factory()' and 'get_my_factory_type()'
diff --git a/t/factory.t b/t/factory.t
index 4ca6ba4..5b69a47 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,93 +1,102 @@
# -*-perl-*-
use strict;
-use Test::More tests => 28;
+use Test::More tests => 32;
use lib qw( ./t ./lib );
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
my @loaded_classes = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes, 1, 'Number of classes loaded so far' );
is( $loaded_classes[0], 'MyRockBand', 'Default class added' );
my @loaded_types = MySimpleBand->get_loaded_types;
is( scalar @loaded_types, 1, 'Number of types loaded so far' );
is( $loaded_types[0], 'rock', 'Default type added' );
my @registered_classes = MySimpleBand->get_registered_classes;
is( scalar @registered_classes, 1, 'Number of classes registered so far' );
is( $registered_classes[0], 'MyCountryBand', 'Default class registered' );
my @registered_types = MySimpleBand->get_registered_types;
is( scalar @registered_types, 1, 'Number of types registered so far' );
is( $registered_types[0], 'country', 'Default type registered' );
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Type of added object returned' );
is( $rock->band_name(), $rock_band,
'Added object type super init parameter set' );
is( $rock->genre(), $rock_genre,
'Added object type self init parameter set' );
+ is( $rock->get_my_factory, 'MySimpleBand',
+ 'Factory class retrievable from object' );
+ is( $rock->get_my_factory_type, 'rock',
+ 'Factory type retrievable from object' );
+
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Type of registered object returned' );
is( $country->band_name(), $country_band,
'Registered object type super init parameter set' );
is( $country->genre(), $country_genre,
'Registered object type self init parameter set' );
+ is( $country->get_my_factory, 'MySimpleBand',
+ 'Factory class retrievable from object' );
+ is( $country->get_my_factory_type, 'country',
+ 'Factory type retrievable from object' );
my @loaded_classes_new = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes_new, 2, 'Classes loaded after all used' );
is( $loaded_classes_new[0], 'MyCountryBand', 'Default registered class now loaded' );
is( $loaded_classes_new[1], 'MyRockBand', 'Default added class still loaded' );
my @loaded_types_new = MySimpleBand->get_loaded_types;
is( scalar @loaded_types_new, 2, 'Types loaded after all used' );
is( $loaded_types_new[0], 'country', 'Default registered type now loaded' );
is( $loaded_types_new[1], 'rock', 'Default added type still loaded' );
is( MySimpleBand->get_factory_class( 'country' ), 'MyCountryBand',
'Proper class returned for registered type' );
is( MySimpleBand->get_factory_class( 'rock' ), 'MyRockBand',
'Proper class returned for added type' );
# reissue an add to get a warning
MySimpleBand->add_factory_type( rock => 'MyRockBand' );
is( $MySimpleBand::log_msg,
"Attempt to add type 'rock' to 'MySimpleBand' redundant; type already exists with class 'MyRockBand'",
'Generated correct log message with duplicate factory type added' );
# reissue a registration to get a warning
MySimpleBand->register_factory_type( country => 'MyCountryBand' );
is( $MySimpleBand::log_msg,
"Attempt to register type 'country' with 'MySimpleBand' is redundant; type registered with class 'MyCountryBand'",
'Generated correct log message with duplicate factory type registered' );
# generate an error message
MySimpleBand->add_factory_type( disco => 'SomeKeyboardGuy' );
ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
'Generated correct error message when adding nonexistent class' );
# generate an error message when creating an object of a nonexistent class
MySimpleBand->register_factory_type( disco => 'SomeKeyboardGuy' );
my $disco = MySimpleBand->new( 'disco', { shoes => 'white' } );
ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
'Generated correct error message when instantiate object with nonexistent class registration' );
}
|
redhotpenguin/Class-Factory | 2a4463fea7362463df526ec3f147b1ddc80a9ed3 | add dist | diff --git a/dist/Class-Factory-1.02.tar.gz b/dist/Class-Factory-1.02.tar.gz
new file mode 100644
index 0000000..01dc007
Binary files /dev/null and b/dist/Class-Factory-1.02.tar.gz differ
|
redhotpenguin/Class-Factory | aab3866fb1a06a582349eae86b62df49558503d7 | mostly doc and test updates | diff --git a/Changes b/Changes
index 96939c2..b12b9b3 100644
--- a/Changes
+++ b/Changes
@@ -1,52 +1,71 @@
Revision history for Perl extension Class::Factory.
-1.01 Thu Aug 21 22:08:29 EDT 2003
+1.02 Tue Oct 12 21:02:04 EDT 2004
+
+ - Ensure that new() returns undef if get_factory_class() doesn't
+ work properly and factory_error() is overridden (and the
+ overridden method doesn't die)
+
+ - Relatively minor documentation clarifications and additions
+ spurred by a Perlmonks post:
+
+ http://www.perlmonks.org/index.pl?node_id=398257
+
+ - Added a few more tests to ensure factory_log() and
+ factory_error() working properly
+
+
+1.01 (never released for some reason)
- add_factory_type() checks %INC to see if a class is already
loaded. This gets rid of any 'Subroutine foo redefined' messages
you might see if warnings are turned on.
- All log/error messages now have variables in apostrophes
rather than brackes. So:
"Class [$class] not found"
becomes:
"Class '$class' not found"
It's just cleaner that way.
+
1.00 Mon Oct 7 11:15:50 EDT 2002
- Add overridable logging/errors (Thanks to Eric Andreychek
<[email protected]>)
- Subclasses do not need to implement any methods any longer --
using the module is a simple 'use base qw( Class::Factory )'
away. (Thanks to Eric for the suggestion.)
- Add get_loaded_types(), get_loaded_classes(),
get_registered_types() and get_registered_classes() so you can
keep track of the factory state.
+
0.03 Sun Feb 10 13:00:20 EST 2002
Added the ability to register a type/class without having
Class::Factory include it. This is useful for modules that want
to know all of their types at startup time but don't want to
bring in a particular class until that type is requested. (See
POD for details.)
+
0.02 Wed Jan 30 00:22:58 EST 2002
Added simple constructor to be inherited as needed. This
constructor automatically calls 'init()', not coincidentally the
name that Class::Base uses. Small variable name changes.
+
0.01 Mon Jan 28 08:35:09 EST 2002
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
diff --git a/MANIFEST b/MANIFEST
index f0a342d..d8b2873 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,10 +1,11 @@
Changes
Makefile.PL
MANIFEST
README
lib/Class/Factory.pm
t/factory.t
t/MyCountryBand.pm
t/MyRockBand.pm
t/MySimpleBand.pm
+META.yml Module meta-data (added by MakeMaker)
diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 6e0a75a..15075de 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,549 +1,598 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '1.01';
+$Class::Factory::VERSION = '1.02';
my %INCLUDE = ();
my %REGISTER = ();
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
+ return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $factory_class = $INCLUDE{ $class }->{ $object_type };
return $factory_class if ( $factory_class );
$factory_class = $REGISTER{ $class }->{ $object_type };
if ( $factory_class ) {
- $class->add_factory_type( $object_type, $factory_class );
- return $factory_class;
+ my $added_class =
+ $class->add_factory_type( $object_type, $factory_class );
+ return $added_class;
}
$item->factory_error( "Factory type '$object_type' is not defined ",
"in '$class'" );
+ return undef;
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no ",
"type defined");
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class = $INCLUDE{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to add type '$object_type' to '$class' ",
"redundant; type already exists with class ",
"'$set_object_class'" );
return;
}
# Make sure the object class looks like a perl module/script
# Acceptable formats:
# Module.pm Module.ph Module.pl Module
$object_class =~ m/^([\w:-]+(?:\.(?:pm|ph|pl))?)$/;
$object_class = $1;
if ( $INC{ $object_class } ) {
$item->factory_log( "Looks like class '$object_class' was already ",
"included; no further work necessary" );
}
else {
eval "require $object_class";
if ( $@ ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"class '$class': factory class '$object_class' ",
"cannot be required: $@" );
+ return undef;
}
}
return $INCLUDE{ $class }->{ $object_type } = $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to '$class': no type ",
"defined" );
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type '$object_type' to ",
"'$class': no class defined" );
}
my $set_object_class = $REGISTER{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to register type '$object_type' with ",
"'$class' is redundant; type registered with ",
"class '$set_object_class'" );
return;
}
return $REGISTER{ $class }->{ $object_type } = $object_class;
}
sub get_loaded_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $INCLUDE{ $class } eq 'HASH' );
return sort values %{ $INCLUDE{ $class } };
}
sub get_loaded_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $INCLUDE{ $class } eq 'HASH' );
return sort keys %{ $INCLUDE{ $class } };
}
sub get_registered_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort values %{ $REGISTER{ $class } };
}
sub get_registered_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort keys %{ $REGISTER{ $class } };
}
########################################
# Overridable Log / Error
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
-
+
# Add our default types
-
+
# This type is loaded when the statement is run
-
+
__PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
-
+
__PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
-
+
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
- # brought in when 'add_factory_type()' is called
-
+ # brought in via 'require' immediately
+
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
-
- # Registering a new factory type in code --
- # 'Other::Custom::ClassTwo' in brought in when 'new()' is called
- # with type 'custom_two'
-
+
+ # Registering a new factory type in code; 'Other::Custom::ClassTwo'
+ # isn't brought in yet...
+
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
+
+ # ...it's only 'require'd when the first instance of the type is
+ # created
+
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
- # Get all the loaded and registered classes
- my @loaded = My::Factory->get_loaded_classes;
- my @registered = My::Factory->get_registered_classes;
+ # Get all the loaded and registered classes and types
+
+ my @loaded_classes = My::Factory->get_loaded_classes;
+ my @loaded_types = My::Factory->get_loaded_types;
+ my @registered_classes = My::Factory->get_registered_classes;
+ my @registered_types = My::Factory->get_registered_types;
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
-you will be using. For instance, take configuration files. There are
-four basic operations you would want to do with any configuration:
-read the file in, lookup a value, set a value, write the file
-out. There are also many different types of configuration files, and
-you may want users to be able to provide an implementation for their
-own home-grown configuration format.
+you will be using. Configuration files are a good example of
+this. There are four basic operations you would want to do with any
+configuration: read the file in, lookup a value, set a value, write
+the file out. There are also many different types of configuration
+files, and you may want users to be able to provide an implementation
+for their own home-grown configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
-constructor for you:
+constructor for you. Here's a sample interface and our two built-in
+configuration types:
package My::ConfigFactory;
-
+
use strict;
use base qw( Class::Factory );
-
+
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
-
+
__PACKAGE__->add_factory_type( ini => 'My::IniReader' );
__PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
-
+
1;
And then users can add their own subclasses:
package My::CustomConfig;
-
+
use strict;
use base qw( My::ConfigFactory );
-
+
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
-
+
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
-
+
sub read_from_web { ... implementation to read via http ... }
-
+
# Now register my type with the factory
-
+
My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
-
+
1;
-(You may not with to make your factory the same as your interface, but
+(You may not wish to make your factory the same as your interface, but
this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
-
+
use strict;
use My::ConfigFactory;
-
+ use My::CustomConfig; # this adds the factory type 'custom'...
+
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
+ print "Configuration is a: ", ref( $config ), "\n";
+
+Which prints:
+
+ Configuration is a My::CustomConfig
And they can even add their own:
My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
This might not seem like a very big win, and for small standalone
-applications it is not. But when you develop large applications the
-C<(add|register)_factory_type()> step will almost certainly be done at
-application initialization time, hidden away from the eyes of the
-application developer. That developer will only know that she can
+applications probably isn't. But when you develop large applications
+the C<(add|register)_factory_type()> step will almost certainly be
+done at application initialization time, hidden away from the eyes of
+the application developer. That developer will only know that she can
access the different object types as if they are part of the system.
-As you see in the example above, implementation for subclasses is very
+As you see in the example above implementation for subclasses is very
simple -- just add C<Class::Factory> to your inheritance tree and you
are done.
=head2 Gotchas
-All information is stored under the original subclass name. For
-instance, the following will not do what you expect:
+All type-to-class mapping information is stored under the original
+subclass name. So the following will not do what you expect:
package My::Factory;
use base qw( Class::Factory );
+ ...
package My::Implementation;
use base qw( My::Factory );
-
+ ...
My::Implementation->register_factory_type( impl => 'My::Implementation' );
This does not register 'My::Implementation' under 'My::Factory' as you
-would like, it registers the type under 'My::Implementation'. Keep
-everything in the original factory class name and you will be ok.
+would like, it registers the type under 'My::Implementation' because
+that's the class we used to invoke the 'register_factory_type'
+method. Make all C<add_factory_type()> and C<register_factory_type()>
+invocations with the original factory class name and you'll be golden.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
-parses GET/POST parameters. One type is straightforward L<CGI|CGI>,
-one is L<Apache::Request|Apache::Request>. Many systems do not have
+parses GET/POST parameters. One type uses the ubiquitous L<CGI|CGI>
+module, the other uses the faster but rarer
+L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
-that type is requested will be bring that implementation in. To extend
-our example above, we will use the configuration factory:
+that type is requested will we bring that implementation in. To extend
+our configuration example above we'll change the configuration factory
+to use C<register_factory_type()> instead of C<add_factory_type()>:
package My::ConfigFactory;
-
+
use strict;
use base qw( Class::Factory );
-
+
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
-
+
__PACKAGE__->register_factory_type( ini => 'My::IniReader' );
__PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
-
+
1;
-We just changed the calls from C<add_factory_type()> to
-C<register_factory_type>. This way you can leave the actual inclusion
-of the module for people who would actually use it. For our
-configuration example we might have:
+This way you can leave the actual inclusion of the module for people
+who would actually use it. For our configuration example we might
+have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
=head2 Subclassing
Piece of cake:
package My::Factory;
use base qw( Class::Factory );
+or the old-school:
+
+ package My::Factory;
+ use Class::Factory;
+ @My::Factory::ISA = qw( Class::Factory );
+
You can also override two methods for logging/error handling. There
are a few instances where C<Class::Factory> may generate a warning
message, or even a fatal error. Internally, these are handled using
C<warn> and C<die>, respectively.
-This may not always be what you want though. Maybe you have a different
-logging facility you wish to use. Perhaps you have a more sophisticated method
-of handling errors. If this is the case, you are welcome to override either of
-these methods.
+This may not always be what you want though. Maybe you have a
+different logging facility you wish to use. Perhaps you have a more
+sophisticated method of handling errors (like
+L<Log::Log4perl|Log::Log4perl>. If this is the case, you are welcome
+to override either of these methods.
Currently, these two methods are implemented like the following:
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
Assume that instead of using C<warn>, you wish to use
L<Log::Log4perl|Log::Log4perl>. So, in your subclass, you might
override C<factory_log> like so:
sub factory_log {
shift;
my $logger = get_logger;
$logger->warn( @_ );
}
-=head2 Common Usage Pattern
+=head2 Common Usage Pattern: Initializing from the constructor
-This is a very common pattern. Subclasses create an C<init()>
-method that gets called when the object is created:
+This is a very common pattern: Subclasses create an C<init()> method
+that gets called when the object is created:
package My::Factory;
-
+
use strict;
use base qw( Class::Factory );
-
+
1;
-And here is what a subclass might look like:
+And here is what a subclass might look like -- note that it doesn't
+have to subclass C<My::Factory> as our earlier examples did:
package My::Subclass;
-
+
use strict;
use base qw( Class::Accessor );
+
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
-
+
# Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
=head2 Registering Common Types by Default
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
-
+
use strict;
use base qw( Class::Factory );
-
+
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
- My::Factory->register_factory_type( type2 => 'My::Impl::Type1' );
-
+ My::Factory->register_factory_type( type2 => 'My::Impl::Type2' );
+
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
use My::Factory;
-
+
my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );
=head1 METHODS
B<new( $type, @params )>
This is a default constructor you can use. It is quite simple:
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
+ return undef unless ( $class );
my $self = bless( {}, $class );
return $self->init( @params );
}
-We just create a new object of the class associated (from an earlier
-call to C<add|register_factory_type()>) with C<$type> and then call
-the C<init()> method of that object. The C<init()> method should
-return the object, or die on error.
+We just create a new object as a blessed hashref of the class
+associated (from an earlier call to C<add_factory_type()> or
+C<register_factory_type()>) with C<$type> and then call the C<init()>
+method of that object. The C<init()> method should return the object,
+or die on error.
+
+If we do not get a class name from C<get_factory_class()> we issue a
+C<factory_error()> message which typically means we throw a
+C<die>. However, if you've overridden C<factory_error()> and do not
+die, this factory call will return C<undef>.
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>. If C<$object_type> is
associated with a class and that class has already been included, the
class is returned. If C<$object_type> is registered with a class (not
yet included), then we try to C<require> the class. Any errors on the
C<require> bubble up to the caller. If there are no errors, the class
is returned.
Returns: name of class. If a class matching C<$object_type> is not
-found or cannot be C<require>d, then a C<die()> is thrown.
+found or cannot be C<require>d, then a C<die()> (or more specifically,
+a C<factory_error()>) is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
-are not given or if we cannot find C<$object_class> in @INC, then a
-C<die()> is thrown. A C<warn>ing is issued if the type has already
-been added.
+are not given or if we cannot find C<$object_class> in @INC, then we
+call C<factory_error()>. A C<factory_log()> message is issued if the
+type has already been added.
B<register_factory_type( $object_type, $object_class )>
Tells the factory to register a new factory type. This type will be
dynamically included (using C<add_factory_type()> at the first request
for an instance of that type.
Returns: name of class registered if successful. If the proper
-parameters are not given then a C<die()> is thrown. A C<warn>ing is
-issued if the type has already been registered.
+parameters are not given then we call C<factory_error()>. A
+C<factory_log()> message is issued if the type has already been
+registered.
B<get_loaded_classes()>
Returns a sorted list of the currently loaded classes. If no classes
have been loaded yet, returns an empty list.
B<get_loaded_types()>
Returns a sorted list of the currently loaded types. If no classes
have been loaded yet, returns an empty list.
B<get_registered_classes()>
Returns a sorted list of the classes that were ever registered. If no
classes have been registered yet, returns an empty list.
Note that a class can be both registered and loaded since we do not
clear out the registration once a registered class has been loaded on
demand.
B<get_registered_types()>
Returns a sorted list of the types that were ever registered. If no
types have been registered yet, returns an empty list.
Note that a type can be both registered and loaded since we do not
clear out the registration once a registered type has been loaded on
demand.
+B<factory_log( @message )>
+
+Used internally instead of C<warn> so subclasses can override. Default
+implementation just uses C<warn>.
+
+B<factory_error( @message )>
+
+Used internally instead of C<die> so subclasses can override. Default
+implementation just uses C<die>.
+
=head1 COPYRIGHT
-Copyright (c) 2002 Chris Winters. All rights reserved.
+Copyright (c) 2002-2004 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHORS
Chris Winters E<lt>[email protected]<gt>
Eric Andreychek E<lt>[email protected]<gt> implemented overridable
log/error capability and prodded the module into a simpler design.
diff --git a/t/MySimpleBand.pm b/t/MySimpleBand.pm
index fbba5a2..d4e204c 100644
--- a/t/MySimpleBand.pm
+++ b/t/MySimpleBand.pm
@@ -1,31 +1,44 @@
package MySimpleBand;
# $Id$
use strict;
use base qw( Class::Factory );
sub init {
my ( $self, $params ) = @_;
$self->band_name( $params->{band_name} );
return $self;
}
sub band_name {
my ( $self, $name ) = @_;
$self->{band_name} = $name if ( $name );
return $self->{band_name};
}
sub genre {
my ( $self, $genre ) = @_;
$self->{genre} = $genre if ( $genre );
return $self->{genre};
}
+# Use these to hold logging/error messages we can inspect later
+
+$MySimpleBand::log_msg = '';
+$MySimpleBand::error_msg = '';
+
+sub factory_log {
+ shift; $MySimpleBand::log_msg = join( '', @_ );
+}
+
+sub factory_error {
+ shift; $MySimpleBand::error_msg = join( '', @_ );
+}
+
__PACKAGE__->add_factory_type( rock => 'MyRockBand' );
__PACKAGE__->register_factory_type( country => 'MyCountryBand' );
1;
diff --git a/t/factory.t b/t/factory.t
index c502ee7..4ca6ba4 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,70 +1,93 @@
# -*-perl-*-
use strict;
-use Test::More tests => 24;
+use Test::More tests => 28;
use lib qw( ./t ./lib );
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
my @loaded_classes = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes, 1, 'Number of classes loaded so far' );
is( $loaded_classes[0], 'MyRockBand', 'Default class added' );
my @loaded_types = MySimpleBand->get_loaded_types;
is( scalar @loaded_types, 1, 'Number of types loaded so far' );
is( $loaded_types[0], 'rock', 'Default type added' );
my @registered_classes = MySimpleBand->get_registered_classes;
is( scalar @registered_classes, 1, 'Number of classes registered so far' );
is( $registered_classes[0], 'MyCountryBand', 'Default class registered' );
my @registered_types = MySimpleBand->get_registered_types;
is( scalar @registered_types, 1, 'Number of types registered so far' );
is( $registered_types[0], 'country', 'Default type registered' );
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Type of added object returned' );
is( $rock->band_name(), $rock_band,
'Added object type super init parameter set' );
is( $rock->genre(), $rock_genre,
'Added object type self init parameter set' );
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Type of registered object returned' );
is( $country->band_name(), $country_band,
'Registered object type super init parameter set' );
is( $country->genre(), $country_genre,
'Registered object type self init parameter set' );
my @loaded_classes_new = MySimpleBand->get_loaded_classes;
is( scalar @loaded_classes_new, 2, 'Classes loaded after all used' );
is( $loaded_classes_new[0], 'MyCountryBand', 'Default registered class now loaded' );
is( $loaded_classes_new[1], 'MyRockBand', 'Default added class still loaded' );
my @loaded_types_new = MySimpleBand->get_loaded_types;
is( scalar @loaded_types_new, 2, 'Types loaded after all used' );
is( $loaded_types_new[0], 'country', 'Default registered type now loaded' );
is( $loaded_types_new[1], 'rock', 'Default added type still loaded' );
is( MySimpleBand->get_factory_class( 'country' ), 'MyCountryBand',
'Proper class returned for registered type' );
is( MySimpleBand->get_factory_class( 'rock' ), 'MyRockBand',
'Proper class returned for added type' );
+ # reissue an add to get a warning
+ MySimpleBand->add_factory_type( rock => 'MyRockBand' );
+ is( $MySimpleBand::log_msg,
+ "Attempt to add type 'rock' to 'MySimpleBand' redundant; type already exists with class 'MyRockBand'",
+ 'Generated correct log message with duplicate factory type added' );
+
+ # reissue a registration to get a warning
+ MySimpleBand->register_factory_type( country => 'MyCountryBand' );
+ is( $MySimpleBand::log_msg,
+ "Attempt to register type 'country' with 'MySimpleBand' is redundant; type registered with class 'MyCountryBand'",
+ 'Generated correct log message with duplicate factory type registered' );
+
+ # generate an error message
+ MySimpleBand->add_factory_type( disco => 'SomeKeyboardGuy' );
+ ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
+ 'Generated correct error message when adding nonexistent class' );
+
+ # generate an error message when creating an object of a nonexistent class
+ MySimpleBand->register_factory_type( disco => 'SomeKeyboardGuy' );
+ my $disco = MySimpleBand->new( 'disco', { shoes => 'white' } );
+ ok( $MySimpleBand::error_msg =~ /^Cannot add factory type 'disco' to class 'MySimpleBand': factory class 'SomeKeyboardGuy' cannot be required:/,
+ 'Generated correct error message when instantiate object with nonexistent class registration' );
+
}
|
redhotpenguin/Class-Factory | 4077a7fc8aaae78af67d5cf13185a46beb5e1cec | fairly cosmetic naming and other stuff | diff --git a/Changes b/Changes
index a8d5529..96939c2 100644
--- a/Changes
+++ b/Changes
@@ -1,31 +1,52 @@
Revision history for Perl extension Class::Factory.
-0.04
+1.01 Thu Aug 21 22:08:29 EDT 2003
- - Add overridable logging/errors (Thanks to Eric Andreychek
- <[email protected]>)
+ - add_factory_type() checks %INC to see if a class is already
+ loaded. This gets rid of any 'Subroutine foo redefined' messages
+ you might see if warnings are turned on.
- - Subclasses do not need to implement any methods any longer --
- using the module is a simple 'use base qw( Class::Factory )'
- away. (Thanks to Eric for the suggestion.)
+ - All log/error messages now have variables in apostrophes
+ rather than brackes. So:
+
+ "Class [$class] not found"
+
+ becomes:
+
+ "Class '$class' not found"
+
+ It's just cleaner that way.
+
+1.00 Mon Oct 7 11:15:50 EDT 2002
+
+ - Add overridable logging/errors (Thanks to Eric Andreychek
+ <[email protected]>)
+
+ - Subclasses do not need to implement any methods any longer --
+ using the module is a simple 'use base qw( Class::Factory )'
+ away. (Thanks to Eric for the suggestion.)
+
+ - Add get_loaded_types(), get_loaded_classes(),
+ get_registered_types() and get_registered_classes() so you can
+ keep track of the factory state.
0.03 Sun Feb 10 13:00:20 EST 2002
Added the ability to register a type/class without having
Class::Factory include it. This is useful for modules that want
to know all of their types at startup time but don't want to
bring in a particular class until that type is requested. (See
POD for details.)
0.02 Wed Jan 30 00:22:58 EST 2002
Added simple constructor to be inherited as needed. This
constructor automatically calls 'init()', not coincidentally the
name that Class::Base uses. Small variable name changes.
0.01 Mon Jan 28 08:35:09 EST 2002
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
diff --git a/README b/README
index a2bdbd6..1af56e2 100644
--- a/README
+++ b/README
@@ -1,76 +1,73 @@
Class::Factory - Base class for dynamic factory classes
==========================
package My::Factory;
+ use strict;
use base qw( Class::Factory );
- my %TYPES = ();
+ # Add our default types
- # SIMPLE: Let the parent know about our types
+ My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
+ My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
- sub get_factory_map { return \%TYPES }
+ # Register optional types
- # FLEXIBLE: Let the parent know about our types
+ My::Factory->register_factory_type( java => 'My::Factory::Java' );
- sub get_factory_type {
- my ( $class, $type ) = @_;
- return $TYPES{ $type };
- }
+ 1;
- sub set_factory_type {
- my ( $class, $type, $factory_class ) = @_;
- $TYPES{ $type } = $factory_class;
- }
+ # Create new objects using the default types
- # Simple factory contructor
+ my $perl_item = My::Factory->new( 'perl', foo => 'bar' );
+ my $blech_item = My::Factory->new( 'blech', foo => 'baz' );
- sub new {
- my ( $class, $type, $params ) = @_;
- my $factory_class = $class->get_factory_class( $type );
- return bless( $params, $factory_class );
- }
+ # Create new object using the optional type; this library is loaded
+ # on the first use
- # Add our default types
-
- My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
- My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
-
- 1;
+ my $java_item = My::Factory->new( 'java', foo => 'quux' );
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
- my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
+ my $custom_object = My::Factory->new( 'custom', this => 'that' );
+
+ # Register a new factory type in code
+
+ My::Factory->register_factory_type( bleededge => 'Other::Customized::Class' );
+ my $edgy_object = My::Factory->new( 'bleededge', this => 'that' );
See POD for details
INSTALLATION
To install this module perform the typical four-part Perl salute:
perl Makefile.PL
make
make test
make install
DEPENDENCIES
None, although this module was written almost entirely under the
influence of Weezer.
SIDE-EFFECTS
May include headache, insomnia, and growth spurts, although a control
group given English toffees in place had the same effects.
COPYRIGHT AND LICENCE
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
-AUTHOR
+AUTHORS
+
+Chris Winters <[email protected]>
-Chris Winters <[email protected]>
\ No newline at end of file
+ * Eric Andreychek <[email protected]> also helped out with code,
+ testing and good advice.
diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 4d3a010..6e0a75a 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,543 +1,549 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '1.00';
+$Class::Factory::VERSION = '1.01';
my %INCLUDE = ();
my %REGISTER = ();
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $factory_class = $INCLUDE{ $class }->{ $object_type };
return $factory_class if ( $factory_class );
$factory_class = $REGISTER{ $class }->{ $object_type };
if ( $factory_class ) {
$class->add_factory_type( $object_type, $factory_class );
return $factory_class;
}
- $item->factory_error( "Factory type [$object_type] is not defined ",
- "in [$class]" );
+ $item->factory_error( "Factory type '$object_type' is not defined ",
+ "in '$class'" );
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
- $item->factory_error( "Cannot add factory type to [$class]: no ",
+ $item->factory_error( "Cannot add factory type to '$class': no ",
"type defined");
}
unless ( $object_class ) {
- $item->factory_error( "Cannot add factory type [$object_type] to ",
- "[$class]: no class defined" );
+ $item->factory_error( "Cannot add factory type '$object_type' to ",
+ "'$class': no class defined" );
}
my $set_object_class = $INCLUDE{ $class }->{ $object_type };
if ( $set_object_class ) {
- $item->factory_log( "Attempt to add type [$object_type] to [$class] ",
+ $item->factory_log( "Attempt to add type '$object_type' to '$class' ",
"redundant; type already exists with class ",
- "[$set_object_class]" );
+ "'$set_object_class'" );
return;
}
# Make sure the object class looks like a perl module/script
# Acceptable formats:
# Module.pm Module.ph Module.pl Module
$object_class =~ m/^([\w:-]+(?:\.(?:pm|ph|pl))?)$/;
$object_class = $1;
- eval "require $object_class";
- if ( $@ ) {
- $item->factory_error( "Cannot add factory type [$object_type] to ",
- "class [$class]: factory class [$object_class] ",
- "cannot be required [$@]" );
+ if ( $INC{ $object_class } ) {
+ $item->factory_log( "Looks like class '$object_class' was already ",
+ "included; no further work necessary" );
+ }
+ else {
+ eval "require $object_class";
+ if ( $@ ) {
+ $item->factory_error( "Cannot add factory type '$object_type' to ",
+ "class '$class': factory class '$object_class' ",
+ "cannot be required: $@" );
+ }
}
return $INCLUDE{ $class }->{ $object_type } = $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
- $item->factory_error( "Cannot add factory type to [$class]: no type ",
+ $item->factory_error( "Cannot add factory type to '$class': no type ",
"defined" );
}
unless ( $object_class ) {
- $item->factory_error( "Cannot add factory type [$object_type] to ",
- "[$class]: no class defined" );
+ $item->factory_error( "Cannot add factory type '$object_type' to ",
+ "'$class': no class defined" );
}
my $set_object_class = $REGISTER{ $class }->{ $object_type };
if ( $set_object_class ) {
- $item->factory_log( "Attempt to register type [$object_type] with ",
- "[$class] is redundant; type registered with ",
- "class [$set_object_class]" );
+ $item->factory_log( "Attempt to register type '$object_type' with ",
+ "'$class' is redundant; type registered with ",
+ "class '$set_object_class'" );
return;
}
return $REGISTER{ $class }->{ $object_type } = $object_class;
}
sub get_loaded_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $INCLUDE{ $class } eq 'HASH' );
return sort values %{ $INCLUDE{ $class } };
}
sub get_loaded_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $INCLUDE{ $class } eq 'HASH' );
return sort keys %{ $INCLUDE{ $class } };
}
sub get_registered_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort values %{ $REGISTER{ $class } };
}
sub get_registered_types {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort keys %{ $REGISTER{ $class } };
}
########################################
# Overridable Log / Error
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
# Add our default types
# This type is loaded when the statement is run
__PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
__PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
# brought in when 'add_factory_type()' is called
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
# Registering a new factory type in code --
# 'Other::Custom::ClassTwo' in brought in when 'new()' is called
# with type 'custom_two'
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
# Get all the loaded and registered classes
my @loaded = My::Factory->get_loaded_classes;
my @registered = My::Factory->get_registered_classes;
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. For instance, take configuration files. There are
four basic operations you would want to do with any configuration:
read the file in, lookup a value, set a value, write the file
out. There are also many different types of configuration files, and
you may want users to be able to provide an implementation for their
own home-grown configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->add_factory_type( ini => 'My::IniReader' );
__PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
# Now register my type with the factory
My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
1;
(You may not with to make your factory the same as your interface, but
this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
And they can even add their own:
My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
This might not seem like a very big win, and for small standalone
applications it is not. But when you develop large applications the
C<(add|register)_factory_type()> step will almost certainly be done at
application initialization time, hidden away from the eyes of the
application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above, implementation for subclasses is very
simple -- just add C<Class::Factory> to your inheritance tree and you
are done.
=head2 Gotchas
All information is stored under the original subclass name. For
instance, the following will not do what you expect:
package My::Factory;
use base qw( Class::Factory );
package My::Implementation;
use base qw( My::Factory );
My::Implementation->register_factory_type( impl => 'My::Implementation' );
This does not register 'My::Implementation' under 'My::Factory' as you
would like, it registers the type under 'My::Implementation'. Keep
everything in the original factory class name and you will be ok.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
parses GET/POST parameters. One type is straightforward L<CGI|CGI>,
one is L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
that type is requested will be bring that implementation in. To extend
our example above, we will use the configuration factory:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->register_factory_type( ini => 'My::IniReader' );
__PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
1;
We just changed the calls from C<add_factory_type()> to
C<register_factory_type>. This way you can leave the actual inclusion
of the module for people who would actually use it. For our
configuration example we might have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
=head2 Subclassing
Piece of cake:
package My::Factory;
use base qw( Class::Factory );
You can also override two methods for logging/error handling. There
are a few instances where C<Class::Factory> may generate a warning
message, or even a fatal error. Internally, these are handled using
C<warn> and C<die>, respectively.
This may not always be what you want though. Maybe you have a different
logging facility you wish to use. Perhaps you have a more sophisticated method
of handling errors. If this is the case, you are welcome to override either of
these methods.
Currently, these two methods are implemented like the following:
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
Assume that instead of using C<warn>, you wish to use
L<Log::Log4perl|Log::Log4perl>. So, in your subclass, you might
override C<factory_log> like so:
sub factory_log {
shift;
my $logger = get_logger;
$logger->warn( @_ );
}
=head2 Common Usage Pattern
This is a very common pattern. Subclasses create an C<init()>
method that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
1;
And here is what a subclass might look like:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
=head2 Registering Common Types by Default
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
use strict;
use base qw( Class::Factory );
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type1' );
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
use My::Factory;
my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );
=head1 METHODS
B<new( $type, @params )>
This is a default constructor you can use. It is quite simple:
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
my $self = bless( {}, $class );
return $self->init( @params );
}
We just create a new object of the class associated (from an earlier
call to C<add|register_factory_type()>) with C<$type> and then call
the C<init()> method of that object. The C<init()> method should
return the object, or die on error.
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>. If C<$object_type> is
associated with a class and that class has already been included, the
class is returned. If C<$object_type> is registered with a class (not
yet included), then we try to C<require> the class. Any errors on the
C<require> bubble up to the caller. If there are no errors, the class
is returned.
Returns: name of class. If a class matching C<$object_type> is not
found or cannot be C<require>d, then a C<die()> is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then a
C<die()> is thrown. A C<warn>ing is issued if the type has already
been added.
B<register_factory_type( $object_type, $object_class )>
Tells the factory to register a new factory type. This type will be
dynamically included (using C<add_factory_type()> at the first request
for an instance of that type.
Returns: name of class registered if successful. If the proper
parameters are not given then a C<die()> is thrown. A C<warn>ing is
issued if the type has already been registered.
B<get_loaded_classes()>
Returns a sorted list of the currently loaded classes. If no classes
have been loaded yet, returns an empty list.
B<get_loaded_types()>
Returns a sorted list of the currently loaded types. If no classes
have been loaded yet, returns an empty list.
B<get_registered_classes()>
Returns a sorted list of the classes that were ever registered. If no
classes have been registered yet, returns an empty list.
Note that a class can be both registered and loaded since we do not
clear out the registration once a registered class has been loaded on
demand.
B<get_registered_types()>
Returns a sorted list of the types that were ever registered. If no
types have been registered yet, returns an empty list.
Note that a type can be both registered and loaded since we do not
clear out the registration once a registered type has been loaded on
demand.
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHORS
Chris Winters E<lt>[email protected]<gt>
Eric Andreychek E<lt>[email protected]<gt> implemented overridable
log/error capability and prodded the module into a simpler design.
diff --git a/t/factory.t b/t/factory.t
index cb99a9d..c502ee7 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,57 +1,70 @@
# -*-perl-*-
use strict;
-use Test::More tests => 17;
+use Test::More tests => 24;
use lib qw( ./t ./lib );
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
- my @loaded = MySimpleBand->get_loaded_classes;
- is( scalar @loaded, 1, 'Number of classes loaded so far' );
- is( $loaded[0], 'MyRockBand', 'Default class added' );
+ my @loaded_classes = MySimpleBand->get_loaded_classes;
+ is( scalar @loaded_classes, 1, 'Number of classes loaded so far' );
+ is( $loaded_classes[0], 'MyRockBand', 'Default class added' );
- my @registered = MySimpleBand->get_registered_classes;
- is( scalar @registered, 1, 'Number of classes registered so far' );
- is( $registered[0], 'MyCountryBand', 'Default class registered' );
+ my @loaded_types = MySimpleBand->get_loaded_types;
+ is( scalar @loaded_types, 1, 'Number of types loaded so far' );
+ is( $loaded_types[0], 'rock', 'Default type added' );
+
+ my @registered_classes = MySimpleBand->get_registered_classes;
+ is( scalar @registered_classes, 1, 'Number of classes registered so far' );
+ is( $registered_classes[0], 'MyCountryBand', 'Default class registered' );
+
+ my @registered_types = MySimpleBand->get_registered_types;
+ is( scalar @registered_types, 1, 'Number of types registered so far' );
+ is( $registered_types[0], 'country', 'Default type registered' );
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Type of added object returned' );
is( $rock->band_name(), $rock_band,
'Added object type super init parameter set' );
is( $rock->genre(), $rock_genre,
'Added object type self init parameter set' );
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Type of registered object returned' );
is( $country->band_name(), $country_band,
'Registered object type super init parameter set' );
is( $country->genre(), $country_genre,
'Registered object type self init parameter set' );
- my @loaded_new = MySimpleBand->get_loaded_classes;
- is( scalar @loaded_new, 2, 'Classes loaded after all used' );
- is( $loaded_new[0], 'MyCountryBand', 'Default registered class now loaded' );
- is( $loaded_new[1], 'MyRockBand', 'Default added class still loaded' );
+ my @loaded_classes_new = MySimpleBand->get_loaded_classes;
+ is( scalar @loaded_classes_new, 2, 'Classes loaded after all used' );
+ is( $loaded_classes_new[0], 'MyCountryBand', 'Default registered class now loaded' );
+ is( $loaded_classes_new[1], 'MyRockBand', 'Default added class still loaded' );
+
+ my @loaded_types_new = MySimpleBand->get_loaded_types;
+ is( scalar @loaded_types_new, 2, 'Types loaded after all used' );
+ is( $loaded_types_new[0], 'country', 'Default registered type now loaded' );
+ is( $loaded_types_new[1], 'rock', 'Default added type still loaded' );
is( MySimpleBand->get_factory_class( 'country' ), 'MyCountryBand',
'Proper class returned for registered type' );
is( MySimpleBand->get_factory_class( 'rock' ), 'MyRockBand',
'Proper class returned for added type' );
}
|
redhotpenguin/Class-Factory | 7dd06caa180f88cd4cd30dfc90687afb4f216e63 | add loaded/registered types | diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index e2e3793..4d3a010 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,515 +1,543 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '0.04';
+$Class::Factory::VERSION = '1.00';
my %INCLUDE = ();
my %REGISTER = ();
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $factory_class = $INCLUDE{ $class }->{ $object_type };
return $factory_class if ( $factory_class );
$factory_class = $REGISTER{ $class }->{ $object_type };
if ( $factory_class ) {
$class->add_factory_type( $object_type, $factory_class );
return $factory_class;
}
$item->factory_error( "Factory type [$object_type] is not defined ",
"in [$class]" );
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to [$class]: no ",
"type defined");
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type [$object_type] to ",
"[$class]: no class defined" );
}
my $set_object_class = $INCLUDE{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to add type [$object_type] to [$class] ",
"redundant; type already exists with class ",
"[$set_object_class]" );
return;
}
# Make sure the object class looks like a perl module/script
# Acceptable formats:
# Module.pm Module.ph Module.pl Module
$object_class =~ m/^([\w:-]+(?:\.(?:pm|ph|pl))?)$/;
$object_class = $1;
eval "require $object_class";
if ( $@ ) {
$item->factory_error( "Cannot add factory type [$object_type] to ",
"class [$class]: factory class [$object_class] ",
"cannot be required [$@]" );
}
return $INCLUDE{ $class }->{ $object_type } = $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
$item->factory_error( "Cannot add factory type to [$class]: no type ",
"defined" );
}
unless ( $object_class ) {
$item->factory_error( "Cannot add factory type [$object_type] to ",
"[$class]: no class defined" );
}
my $set_object_class = $REGISTER{ $class }->{ $object_type };
if ( $set_object_class ) {
$item->factory_log( "Attempt to register type [$object_type] with ",
"[$class] is redundant; type registered with ",
"class [$set_object_class]" );
return;
}
return $REGISTER{ $class }->{ $object_type } = $object_class;
}
sub get_loaded_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $INCLUDE{ $class } eq 'HASH' );
return sort values %{ $INCLUDE{ $class } };
}
+sub get_loaded_types {
+ my ( $item ) = @_;
+ my $class = ref $item || $item;
+ return () unless ( ref $INCLUDE{ $class } eq 'HASH' );
+ return sort keys %{ $INCLUDE{ $class } };
+}
+
sub get_registered_classes {
my ( $item ) = @_;
my $class = ref $item || $item;
return () unless ( ref $REGISTER{ $class } eq 'HASH' );
return sort values %{ $REGISTER{ $class } };
}
+sub get_registered_types {
+ my ( $item ) = @_;
+ my $class = ref $item || $item;
+ return () unless ( ref $REGISTER{ $class } eq 'HASH' );
+ return sort keys %{ $REGISTER{ $class } };
+}
+
########################################
# Overridable Log / Error
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
# Add our default types
# This type is loaded when the statement is run
__PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
__PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
# brought in when 'add_factory_type()' is called
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
# Registering a new factory type in code --
# 'Other::Custom::ClassTwo' in brought in when 'new()' is called
# with type 'custom_two'
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
# Get all the loaded and registered classes
my @loaded = My::Factory->get_loaded_classes;
my @registered = My::Factory->get_registered_classes;
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. For instance, take configuration files. There are
four basic operations you would want to do with any configuration:
read the file in, lookup a value, set a value, write the file
out. There are also many different types of configuration files, and
you may want users to be able to provide an implementation for their
own home-grown configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->add_factory_type( ini => 'My::IniReader' );
__PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
# Now register my type with the factory
My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
1;
(You may not with to make your factory the same as your interface, but
this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
And they can even add their own:
My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
This might not seem like a very big win, and for small standalone
applications it is not. But when you develop large applications the
C<(add|register)_factory_type()> step will almost certainly be done at
application initialization time, hidden away from the eyes of the
application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above, implementation for subclasses is very
simple -- just add C<Class::Factory> to your inheritance tree and you
are done.
=head2 Gotchas
All information is stored under the original subclass name. For
instance, the following will not do what you expect:
package My::Factory;
use base qw( Class::Factory );
package My::Implementation;
use base qw( My::Factory );
My::Implementation->register_factory_type( impl => 'My::Implementation' );
This does not register 'My::Implementation' under 'My::Factory' as you
would like, it registers the type under 'My::Implementation'. Keep
everything in the original factory class name and you will be ok.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
parses GET/POST parameters. One type is straightforward L<CGI|CGI>,
one is L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
that type is requested will be bring that implementation in. To extend
our example above, we will use the configuration factory:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
__PACKAGE__->register_factory_type( ini => 'My::IniReader' );
__PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
1;
We just changed the calls from C<add_factory_type()> to
C<register_factory_type>. This way you can leave the actual inclusion
of the module for people who would actually use it. For our
configuration example we might have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
=head2 Subclassing
Piece of cake:
package My::Factory;
use base qw( Class::Factory );
You can also override two methods for logging/error handling. There
are a few instances where C<Class::Factory> may generate a warning
message, or even a fatal error. Internally, these are handled using
C<warn> and C<die>, respectively.
This may not always be what you want though. Maybe you have a different
logging facility you wish to use. Perhaps you have a more sophisticated method
of handling errors. If this is the case, you are welcome to override either of
these methods.
Currently, these two methods are implemented like the following:
sub factory_log { shift; warn @_, "\n" }
sub factory_error { shift; die @_, "\n" }
Assume that instead of using C<warn>, you wish to use
L<Log::Log4perl|Log::Log4perl>. So, in your subclass, you might
override C<factory_log> like so:
sub factory_log {
shift;
my $logger = get_logger;
$logger->warn( @_ );
}
=head2 Common Usage Pattern
This is a very common pattern. Subclasses create an C<init()>
method that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
1;
And here is what a subclass might look like:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
=head2 Registering Common Types by Default
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
use strict;
use base qw( Class::Factory );
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type1' );
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
use My::Factory;
my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );
=head1 METHODS
B<new( $type, @params )>
This is a default constructor you can use. It is quite simple:
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
my $self = bless( {}, $class );
return $self->init( @params );
}
We just create a new object of the class associated (from an earlier
call to C<add|register_factory_type()>) with C<$type> and then call
the C<init()> method of that object. The C<init()> method should
return the object, or die on error.
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>. If C<$object_type> is
associated with a class and that class has already been included, the
class is returned. If C<$object_type> is registered with a class (not
yet included), then we try to C<require> the class. Any errors on the
C<require> bubble up to the caller. If there are no errors, the class
is returned.
Returns: name of class. If a class matching C<$object_type> is not
found or cannot be C<require>d, then a C<die()> is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then a
C<die()> is thrown. A C<warn>ing is issued if the type has already
been added.
B<register_factory_type( $object_type, $object_class )>
Tells the factory to register a new factory type. This type will be
dynamically included (using C<add_factory_type()> at the first request
for an instance of that type.
Returns: name of class registered if successful. If the proper
parameters are not given then a C<die()> is thrown. A C<warn>ing is
issued if the type has already been registered.
B<get_loaded_classes()>
Returns a sorted list of the currently loaded classes. If no classes
have been loaded yet, returns an empty list.
+B<get_loaded_types()>
+
+Returns a sorted list of the currently loaded types. If no classes
+have been loaded yet, returns an empty list.
+
B<get_registered_classes()>
Returns a sorted list of the classes that were ever registered. If no
-classes have been loaded yet, returns an empty list.
+classes have been registered yet, returns an empty list.
Note that a class can be both registered and loaded since we do not
clear out the registration once a registered class has been loaded on
demand.
+B<get_registered_types()>
+
+Returns a sorted list of the types that were ever registered. If no
+types have been registered yet, returns an empty list.
+
+Note that a type can be both registered and loaded since we do not
+clear out the registration once a registered type has been loaded on
+demand.
+
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHORS
Chris Winters E<lt>[email protected]<gt>
Eric Andreychek E<lt>[email protected]<gt> implemented overridable
log/error capability and prodded the module into a simpler design.
|
redhotpenguin/Class-Factory | 1d43076fc95a6620d9bbc9e20c273589162a81b1 | latest changes (few of them :-) | diff --git a/Changes b/Changes
index 4c66709..a8d5529 100644
--- a/Changes
+++ b/Changes
@@ -1,22 +1,31 @@
Revision history for Perl extension Class::Factory.
+0.04
+
+ - Add overridable logging/errors (Thanks to Eric Andreychek
+ <[email protected]>)
+
+ - Subclasses do not need to implement any methods any longer --
+ using the module is a simple 'use base qw( Class::Factory )'
+ away. (Thanks to Eric for the suggestion.)
+
0.03 Sun Feb 10 13:00:20 EST 2002
Added the ability to register a type/class without having
Class::Factory include it. This is useful for modules that want
to know all of their types at startup time but don't want to
bring in a particular class until that type is requested. (See
POD for details.)
0.02 Wed Jan 30 00:22:58 EST 2002
Added simple constructor to be inherited as needed. This
constructor automatically calls 'init()', not coincidentally the
name that Class::Base uses. Small variable name changes.
0.01 Mon Jan 28 08:35:09 EST 2002
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
diff --git a/MANIFEST b/MANIFEST
index b4548ac..f0a342d 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,11 +1,10 @@
Changes
Makefile.PL
MANIFEST
README
lib/Class/Factory.pm
t/factory.t
t/MyCountryBand.pm
-t/MyFlexibleBand.pm
t/MyRockBand.pm
t/MySimpleBand.pm
diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 03c6366..e2e3793 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,565 +1,515 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '0.03';
+$Class::Factory::VERSION = '0.04';
+
+my %INCLUDE = ();
+my %REGISTER = ();
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
- my $map = $item->get_factory_map;
- my $factory_class = ( ref $map eq 'HASH' )
- ? $map->{ $object_type }
- : $item->get_factory_type( $object_type );
+ my $factory_class = $INCLUDE{ $class }->{ $object_type };
return $factory_class if ( $factory_class );
- my $register_map = $item->get_register_map;
- $factory_class = ( ref $register_map eq 'HASH' )
- ? $register_map->{ $object_type }
- : $item->get_register_type( $object_type );
+ $factory_class = $REGISTER{ $class }->{ $object_type };
if ( $factory_class ) {
- $item->add_factory_type( $object_type, $factory_class );
+ $class->add_factory_type( $object_type, $factory_class );
return $factory_class;
}
- die "Factory type [$object_type] is not defined in [$class]\n";
+ $item->factory_error( "Factory type [$object_type] is not defined ",
+ "in [$class]" );
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
- die "Cannot add factory type to [$class]: no type defined\n";
+ $item->factory_error( "Cannot add factory type to [$class]: no ",
+ "type defined");
}
unless ( $object_class ) {
- die "Cannot add factory type [$object_type] to [$class]: no class defined\n";
+ $item->factory_error( "Cannot add factory type [$object_type] to ",
+ "[$class]: no class defined" );
}
- my $map = $item->get_factory_map;
- my $set_object_class = ( ref $map eq 'HASH' )
- ? $map->{ $object_type }
- : $item->get_factory_type( $object_type );
+ my $set_object_class = $INCLUDE{ $class }->{ $object_type };
if ( $set_object_class ) {
- warn "Attempt to add type [$object_type] to [$class] redundant; ",
- "type already exists with class [$set_object_class]\n";
+ $item->factory_log( "Attempt to add type [$object_type] to [$class] ",
+ "redundant; type already exists with class ",
+ "[$set_object_class]" );
return;
}
+ # Make sure the object class looks like a perl module/script
+ # Acceptable formats:
+ # Module.pm Module.ph Module.pl Module
+ $object_class =~ m/^([\w:-]+(?:\.(?:pm|ph|pl))?)$/;
+ $object_class = $1;
+
eval "require $object_class";
if ( $@ ) {
- die "Cannot add factory type [$object_type] to class [$class]: ",
- "factory class [$object_class] cannot be required [$@]\n";
- }
-
- if ( ref $map eq 'HASH' ) {
- $map->{ $object_type } = $object_class;
- }
- else {
- $item->set_factory_type( $object_type, $object_class );
+ $item->factory_error( "Cannot add factory type [$object_type] to ",
+ "class [$class]: factory class [$object_class] ",
+ "cannot be required [$@]" );
}
- return $object_class;
+ return $INCLUDE{ $class }->{ $object_type } = $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
- die "Cannot add factory type to [$class]: no type defined\n";
+ $item->factory_error( "Cannot add factory type to [$class]: no type ",
+ "defined" );
}
unless ( $object_class ) {
- die "Cannot add factory type [$object_type] to [$class]: no class defined\n";
+ $item->factory_error( "Cannot add factory type [$object_type] to ",
+ "[$class]: no class defined" );
}
- my $map = $item->get_register_map;
- my $set_object_class = ( ref $map eq 'HASH' )
- ? $map->{ $object_type }
- : $item->get_register_type( $object_type );
+ my $set_object_class = $REGISTER{ $class }->{ $object_type };
if ( $set_object_class ) {
- warn "Attempt to register type [$object_type] with [$class] is",
- "redundant; type registered with class [$set_object_class]\n";
+ $item->factory_log( "Attempt to register type [$object_type] with ",
+ "[$class] is redundant; type registered with ",
+ "class [$set_object_class]" );
return;
}
- if ( ref $map eq 'HASH' ) {
- $map->{ $object_type } = $object_class;
- }
- else {
- $item->set_register_type( $object_type, $object_class );
- }
+ return $REGISTER{ $class }->{ $object_type } = $object_class;
}
-########################################
-# INTERFACE
+sub get_loaded_classes {
+ my ( $item ) = @_;
+ my $class = ref $item || $item;
+ return () unless ( ref $INCLUDE{ $class } eq 'HASH' );
+ return sort values %{ $INCLUDE{ $class } };
+}
-# We don't die when these are called because the subclass can define
-# either A + B or C
+sub get_registered_classes {
+ my ( $item ) = @_;
+ my $class = ref $item || $item;
+ return () unless ( ref $REGISTER{ $class } eq 'HASH' );
+ return sort values %{ $REGISTER{ $class } };
+}
+
+########################################
+# Overridable Log / Error
-sub get_factory_type { return undef }
-sub set_factory_type { return undef }
-sub get_factory_map { return undef }
-sub get_register_type { return undef }
-sub set_register_type { return undef }
-sub get_register_map { return undef }
+sub factory_log { shift; warn @_, "\n" }
+sub factory_error { shift; die @_, "\n" }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
-
use base qw( Class::Factory );
- my %TYPES = ();
-
- # SIMPLE: Let the parent know about our types
-
- sub get_factory_map { return \%TYPES }
-
- # FLEXIBLE: Let the parent know about our types
-
- sub get_factory_type {
- my ( $class, $type ) = @_;
- return $TYPES{ $type };
- }
-
- sub set_factory_type {
- my ( $class, $type, $factory_class ) = @_;
- $TYPES{ $type } = $factory_class;
- }
-
- # LAZY LOADING: Allow subclasses to register a type without loading
- # its class
-
- my %REGISTERED = ();
-
- # SIMPLE LAZY LOAD: Let the parent know about registered types
-
- sub get_register_map { return \%REGISTERED }
-
- # FLEXIBLE LAZY LOAD: Let the parent know about registered types
-
- sub get_register_type {
- my ( $class, $type ) = @_;
- return $REGISTERED{ $type };
- }
-
- sub set_register_type {
- my ( $class, $type, $factory_class ) = @_;
- $REGISTERED{ $type } = $factory_class;
- }
-
-
# Add our default types
# This type is loaded when the statement is run
- My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
+ __PACKAGE__->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
- My::Factory->register_factory_type( blech => 'My::Factory::Blech' );
+ __PACKAGE__->register_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
# brought in when 'add_factory_type()' is called
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
# Registering a new factory type in code --
# 'Other::Custom::ClassTwo' in brought in when 'new()' is called
# with type 'custom_two'
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
+ # Get all the loaded and registered classes
+ my @loaded = My::Factory->get_loaded_classes;
+ my @registered = My::Factory->get_registered_classes;
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. For instance, take configuration files. There are
-four basic operations you would want to do with any configuration
-file: read it in, lookup a value, set a value, write it out. There are
-also many different types of configuration files, and you may want
-users to be able to provide an implementation for their own home-grown
-configuration format.
+four basic operations you would want to do with any configuration:
+read the file in, lookup a value, set a value, write the file
+out. There are also many different types of configuration files, and
+you may want users to be able to provide an implementation for their
+own home-grown configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
- my %TYPES = ();
- sub get_factory_map { return \%TYPES }
-
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
+ __PACKAGE__->add_factory_type( ini => 'My::IniReader' );
+ __PACKAGE__->add_factory_type( perl => 'My::PerlReader' );
+
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
+ # Now register my type with the factory
+
+ My::ConfigFactory->add_factory_type( 'mytype' => __PACKAGE__ );
+
1;
-(Normally you probably would not make your factory the same as your
-interface, but this is an abbreviated example.)
+(You may not with to make your factory the same as your interface, but
+this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
- My::ConfigFactory->add_factory_type( 'custom' => 'My::CustomConfig' );
-
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
+And they can even add their own:
+
+ My::ConfigFactory->register_factory_type( 'newtype' => 'My::New::ConfigReader' );
+
This might not seem like a very big win, and for small standalone
applications it is not. But when you develop large applications the
-C<add_factory_type()> step will almost certainly be done at
+C<(add|register)_factory_type()> step will almost certainly be done at
application initialization time, hidden away from the eyes of the
application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above, implementation for subclasses is very
-simple. The base class defines two methods for subclasses to use:
-C<get_factory_class()> and C<add_factory_type()>. Subclasses must
-define either C<get_factory_map()> or both C<get_factory_type()> and
-C<set_factory_type()>.
+simple -- just add C<Class::Factory> to your inheritance tree and you
+are done.
+
+=head2 Gotchas
+
+All information is stored under the original subclass name. For
+instance, the following will not do what you expect:
+
+ package My::Factory;
+ use base qw( Class::Factory );
+
+ package My::Implementation;
+ use base qw( My::Factory );
+
+ My::Implementation->register_factory_type( impl => 'My::Implementation' );
+
+This does not register 'My::Implementation' under 'My::Factory' as you
+would like, it registers the type under 'My::Implementation'. Keep
+everything in the original factory class name and you will be ok.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
parses GET/POST parameters. One type is straightforward L<CGI|CGI>,
one is L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
that type is requested will be bring that implementation in. To extend
our example above, we will use the configuration factory:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
- my %TYPES = ();
- sub get_factory_map { return \%TYPES }
- my %REGISTERED = ();
- sub get_register_map { return \%REGISTERED }
-
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
+ __PACKAGE__->register_factory_type( ini => 'My::IniReader' );
+ __PACKAGE__->register_factory_type( perl => 'My::PerlReader' );
+
1;
-We only added two lines. But now we can register configuration types
-for modules that the user might not have:
+We just changed the calls from C<add_factory_type()> to
+C<register_factory_type>. This way you can leave the actual inclusion
+of the module for people who would actually use it. For our
+configuration example we might have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
-=head1 METHODS
+=head2 Subclassing
-B<new( $type, @params )>
-
-This is a default constructor you can use. It is quite simple:
-
- sub new {
- my ( $pkg, $type, @params ) = @_;
- my $class = $pkg->get_factory_class( $type );
- my $self = bless( {}, $class );
- return $self->init( @params );
- }
-
-We just create a new object of the class associated (from an earlier
-call to C<add_factory_type()>) with C<$type> and then call the
-C<init()> method of that object. The C<init()> method should return
-the object, or die on error.
-
-B<get_factory_class( $object_type )>
-
-Usually called from a constructor when you want to lookup a class by a
-type and create a new object of C<$object_type>.
-
-Returns: name of class. If a class matching C<$object_type> is not
-found, then a C<die()> is thrown.
-
-B<add_factory_type( $object_type, $object_class )>
-
-Tells the factory to dynamically add a new type to its stable and
-brings in the class implementing that type using C<require()>. After
-running this the factory class will be able to create new objects of
-type C<$object_type>.
-
-Returns: name of class added if successful. If the proper parameters
-are not given or if we cannot find C<$object_class> in @INC, then a
-C<die()> is thrown. A C<warn>ing is issued if the type has already
-been added.
-
-B<register_factory_type( $object_type, $object_class )>
-
-Tells the factory to register a new factory type. This type will be
-dynamically included (using C<add_factory_type()> at the first request
-for an instance of that type.
-
-Returns: name of class registered if successful. If the proper
-parameters are not given then a C<die()> is thrown. A C<warn>ing is
-issued if the type has already been registered.
-
-=head1 SUBCLASSING
-
-You can do this either the simple way or the flexible way. For most
-cases, the simple way will suffice:
+Piece of cake:
package My::Factory;
-
use base qw( Class::Factory );
- my %TYPES = ();
- sub get_factory_map { return \%TYPES }
+You can also override two methods for logging/error handling. There
+are a few instances where C<Class::Factory> may generate a warning
+message, or even a fatal error. Internally, these are handled using
+C<warn> and C<die>, respectively.
-If you want to also add the ability to register classes:
+This may not always be what you want though. Maybe you have a different
+logging facility you wish to use. Perhaps you have a more sophisticated method
+of handling errors. If this is the case, you are welcome to override either of
+these methods.
- package My::Factory;
-
- use base qw( Class::Factory );
+Currently, these two methods are implemented like the following:
- my %TYPES = ();
- sub get_factory_map { return \%TYPES }
- my %REGISTERED = ();
- sub get_register_map { return \%REGISTERED }
+ sub factory_log { shift; warn @_, "\n" }
+ sub factory_error { shift; die @_, "\n" }
+Assume that instead of using C<warn>, you wish to use
+L<Log::Log4perl|Log::Log4perl>. So, in your subclass, you might
+override C<factory_log> like so:
-If you elect to use the flexible way, you need to implement two
-methods:
-
- package My::Factory;
-
- use base qw( Class::Factory );
-
- my %TYPES = ();
- sub get_factory_class {
- my ( $class, $type ) = @_;
- return $TYPES{ $type };
- }
-
- sub set_factory_class {
- my ( $class, $type, $object_class ) = @_;
- return $TYPES{ $type } = $object_class;
+ sub factory_log {
+ shift;
+ my $logger = get_logger;
+ $logger->warn( @_ );
}
-And if you want to use the flexible way along with registering types:
-
- package My::Factory;
-
- use base qw( Class::Factory );
-
- my %TYPES = ();
- sub get_factory_class {
- my ( $class, $type ) = @_;
- return $TYPES{ $type };
- }
-
- sub set_factory_class {
- my ( $class, $type, $object_class ) = @_;
- return $TYPES{ $type } = $object_class;
- }
-
- my %REGISTERED = ();
- sub get_register_class {
- my ( $class, $type ) = @_;
- return $REGISTERED{ $type };
- }
-
- sub set_register_class {
- my ( $class, $type, $object_class ) = @_;
- return $REGISTERED{ $type } = $object_class;
- }
-
-
-How these methods work is entirely up to you -- maybe
-C<get_factory_class()> does a lookup in some external resource before
-returning the class. Whatever floats your boat.
-
-=head1 USAGE
-
-=head2 Common Pattern
+=head2 Common Usage Pattern
This is a very common pattern. Subclasses create an C<init()>
method that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
- my %TYPES = ();
- sub get_factory_map { return \%TYPES }
- my %REGISTERED = ();
- sub get_register_map { return \%REGISTERED }
-
1;
And here is what a subclass might look like:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
- # Note: we've taken the flattened C<@params> passed in and assigned
+ # Note: we have taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
-=head2 Registering Types
+=head2 Registering Common Types by Default
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
use strict;
use base qw( Class::Factory );
- my %TYPES = ();
- sub get_factory_map { return \%TYPES }
- my %REGISTERED = ();
- sub get_register_map { return \%REGISTERED }
-
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type1' );
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
use My::Factory;
my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );
+=head1 METHODS
+
+B<new( $type, @params )>
+
+This is a default constructor you can use. It is quite simple:
+
+ sub new {
+ my ( $pkg, $type, @params ) = @_;
+ my $class = $pkg->get_factory_class( $type );
+ my $self = bless( {}, $class );
+ return $self->init( @params );
+ }
+
+We just create a new object of the class associated (from an earlier
+call to C<add|register_factory_type()>) with C<$type> and then call
+the C<init()> method of that object. The C<init()> method should
+return the object, or die on error.
+
+B<get_factory_class( $object_type )>
+
+Usually called from a constructor when you want to lookup a class by a
+type and create a new object of C<$object_type>. If C<$object_type> is
+associated with a class and that class has already been included, the
+class is returned. If C<$object_type> is registered with a class (not
+yet included), then we try to C<require> the class. Any errors on the
+C<require> bubble up to the caller. If there are no errors, the class
+is returned.
+
+Returns: name of class. If a class matching C<$object_type> is not
+found or cannot be C<require>d, then a C<die()> is thrown.
+
+B<add_factory_type( $object_type, $object_class )>
+
+Tells the factory to dynamically add a new type to its stable and
+brings in the class implementing that type using C<require>. After
+running this the factory class will be able to create new objects of
+type C<$object_type>.
+
+Returns: name of class added if successful. If the proper parameters
+are not given or if we cannot find C<$object_class> in @INC, then a
+C<die()> is thrown. A C<warn>ing is issued if the type has already
+been added.
+
+B<register_factory_type( $object_type, $object_class )>
+
+Tells the factory to register a new factory type. This type will be
+dynamically included (using C<add_factory_type()> at the first request
+for an instance of that type.
+
+Returns: name of class registered if successful. If the proper
+parameters are not given then a C<die()> is thrown. A C<warn>ing is
+issued if the type has already been registered.
+
+B<get_loaded_classes()>
+
+Returns a sorted list of the currently loaded classes. If no classes
+have been loaded yet, returns an empty list.
+
+B<get_registered_classes()>
+
+Returns a sorted list of the classes that were ever registered. If no
+classes have been loaded yet, returns an empty list.
+
+Note that a class can be both registered and loaded since we do not
+clear out the registration once a registered class has been loaded on
+demand.
+
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
-=head1 AUTHOR
+=head1 AUTHORS
+
+Chris Winters E<lt>[email protected]<gt>
-Chris Winters <[email protected]>
+Eric Andreychek E<lt>[email protected]<gt> implemented overridable
+log/error capability and prodded the module into a simpler design.
diff --git a/t/MySimpleBand.pm b/t/MySimpleBand.pm
index d9f83e1..fbba5a2 100644
--- a/t/MySimpleBand.pm
+++ b/t/MySimpleBand.pm
@@ -1,39 +1,31 @@
package MySimpleBand;
# $Id$
use strict;
use base qw( Class::Factory );
-#use Class::Factory;
-#@MySimpleBand::ISA = qw( Class::Factory );
-
-my %TYPES = ();
-my %REGISTER = ();
-sub get_factory_map { return \%TYPES }
-sub get_register_map { return \%REGISTER }
-
sub init {
my ( $self, $params ) = @_;
$self->band_name( $params->{band_name} );
return $self;
}
sub band_name {
my ( $self, $name ) = @_;
$self->{band_name} = $name if ( $name );
return $self->{band_name};
}
sub genre {
my ( $self, $genre ) = @_;
$self->{genre} = $genre if ( $genre );
return $self->{genre};
}
-MySimpleBand->add_factory_type( rock => 'MyRockBand' );
-MySimpleBand->register_factory_type( country => 'MyCountryBand' );
+__PACKAGE__->add_factory_type( rock => 'MyRockBand' );
+__PACKAGE__->register_factory_type( country => 'MyCountryBand' );
1;
diff --git a/t/factory.t b/t/factory.t
index c92ac7e..cb99a9d 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,68 +1,57 @@
# -*-perl-*-
use strict;
-use Test::More tests => 23;
+use Test::More tests => 17;
use lib qw( ./t ./lib );
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
- @MyRockBand::ISA = qw( MySimpleBand );
+ @MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
- my $factory_map = MySimpleBand->get_factory_map;
- is( ref( $factory_map ), 'HASH', 'Return of get_factory_map()' );
- is( scalar keys %{ $factory_map }, 1, 'Keys in factory map' );
- is( $factory_map->{rock}, 'MyRockBand', 'Simple type added' );
+ my @loaded = MySimpleBand->get_loaded_classes;
+ is( scalar @loaded, 1, 'Number of classes loaded so far' );
+ is( $loaded[0], 'MyRockBand', 'Default class added' );
- my $register_map = MySimpleBand->get_register_map;
- is( ref( $register_map ), 'HASH', 'Return of get_register_map()' );
- is( scalar keys %{ $register_map }, 1, 'Keys in register map' );
- is( $register_map->{country}, 'MyCountryBand', 'Simple type registered' );
+ my @registered = MySimpleBand->get_registered_classes;
+ is( scalar @registered, 1, 'Number of classes registered so far' );
+ is( $registered[0], 'MyCountryBand', 'Default class registered' );
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
- is( ref( $rock ), 'MyRockBand', 'Simple added object returned' );
- is( $rock->band_name(), $rock_band, 'Simple added super init parameter set' );
- is( $rock->genre(), $rock_genre, 'Simple added self init parameter set' );
+ is( ref( $rock ), 'MyRockBand', 'Type of added object returned' );
+ is( $rock->band_name(), $rock_band,
+ 'Added object type super init parameter set' );
+ is( $rock->genre(), $rock_genre,
+ 'Added object type self init parameter set' );
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
- is( ref( $country ), 'MyCountryBand', 'Simple registered object returned' );
- is( $country->band_name(), $country_band, 'Simple registered object super init parameter set' );
- is( $country->genre(), $country_genre, 'Simple registered object self init parameter set' );
-}
-
-# Next the flexible settting
-
-{
- require_ok( 'MyFlexibleBand' );
-
- # Set the ISA of our two bands to the one we're testing now
-
- @MyRockBand::ISA = qw( MyFlexibleBand );
- @MyCountryBand::ISA = qw( MyFlexibleBand );
-
- is( MyFlexibleBand->get_factory_type( 'rock' ), 'MyRockBand', 'Flexible type added' );
- is( MyFlexibleBand->get_register_type( 'country' ), 'MyCountryBand', 'Flexible type registered' );
-
- my $rock = MyFlexibleBand->new( 'rock', { band_name => $rock_band } );
- is( ref( $rock ), 'MyRockBand', 'Flexible added object returned' );
- is( $rock->band_name(), $rock_band, 'Flexible added object super init parameter set' );
- is( $rock->genre(), $rock_genre, 'Flexible added object self init parameter set' );
+ is( ref( $country ), 'MyCountryBand', 'Type of registered object returned' );
+ is( $country->band_name(), $country_band,
+ 'Registered object type super init parameter set' );
+ is( $country->genre(), $country_genre,
+ 'Registered object type self init parameter set' );
+
+ my @loaded_new = MySimpleBand->get_loaded_classes;
+ is( scalar @loaded_new, 2, 'Classes loaded after all used' );
+ is( $loaded_new[0], 'MyCountryBand', 'Default registered class now loaded' );
+ is( $loaded_new[1], 'MyRockBand', 'Default added class still loaded' );
+
+ is( MySimpleBand->get_factory_class( 'country' ), 'MyCountryBand',
+ 'Proper class returned for registered type' );
+ is( MySimpleBand->get_factory_class( 'rock' ), 'MyRockBand',
+ 'Proper class returned for added type' );
- my $country = MyFlexibleBand->new( 'country', { band_name => $country_band } );
- is( ref( $country ), 'MyCountryBand', 'Flexible registered object returned' );
- is( $country->band_name(), $country_band, 'Flexible registered object super init parameter set' );
- is( $country->genre(), $country_genre, 'Flexible registered object self init parameter set' );
}
|
redhotpenguin/Class-Factory | 47cc200c63722e859cd459553803b38158bee1a7 | cosmetic | diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 6943a55..03c6366 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,569 +1,565 @@
package Class::Factory;
# $Id$
use strict;
$Class::Factory::VERSION = '0.03';
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $map = $item->get_factory_map;
my $factory_class = ( ref $map eq 'HASH' )
? $map->{ $object_type }
: $item->get_factory_type( $object_type );
return $factory_class if ( $factory_class );
my $register_map = $item->get_register_map;
$factory_class = ( ref $register_map eq 'HASH' )
? $register_map->{ $object_type }
: $item->get_register_type( $object_type );
if ( $factory_class ) {
$item->add_factory_type( $object_type, $factory_class );
return $factory_class;
}
die "Factory type [$object_type] is not defined in [$class]\n";
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
die "Cannot add factory type to [$class]: no type defined\n";
}
unless ( $object_class ) {
die "Cannot add factory type [$object_type] to [$class]: no class defined\n";
}
my $map = $item->get_factory_map;
my $set_object_class = ( ref $map eq 'HASH' )
? $map->{ $object_type }
: $item->get_factory_type( $object_type );
if ( $set_object_class ) {
warn "Attempt to add type [$object_type] to [$class] redundant; ",
"type already exists with class [$set_object_class]\n";
return;
}
eval "require $object_class";
if ( $@ ) {
die "Cannot add factory type [$object_type] to class [$class]: ",
"factory class [$object_class] cannot be required [$@]\n";
}
if ( ref $map eq 'HASH' ) {
$map->{ $object_type } = $object_class;
}
else {
$item->set_factory_type( $object_type, $object_class );
}
return $object_class;
}
sub register_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
die "Cannot add factory type to [$class]: no type defined\n";
}
unless ( $object_class ) {
die "Cannot add factory type [$object_type] to [$class]: no class defined\n";
}
my $map = $item->get_register_map;
my $set_object_class = ( ref $map eq 'HASH' )
? $map->{ $object_type }
: $item->get_register_type( $object_type );
if ( $set_object_class ) {
warn "Attempt to register type [$object_type] with [$class] is",
"redundant; type registered with class [$set_object_class]\n";
return;
}
if ( ref $map eq 'HASH' ) {
$map->{ $object_type } = $object_class;
}
else {
$item->set_register_type( $object_type, $object_class );
}
}
########################################
# INTERFACE
# We don't die when these are called because the subclass can define
# either A + B or C
sub get_factory_type { return undef }
sub set_factory_type { return undef }
sub get_factory_map { return undef }
sub get_register_type { return undef }
sub set_register_type { return undef }
sub get_register_map { return undef }
1;
__END__
-=pod
-
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
# SIMPLE: Let the parent know about our types
sub get_factory_map { return \%TYPES }
# FLEXIBLE: Let the parent know about our types
sub get_factory_type {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_type {
my ( $class, $type, $factory_class ) = @_;
$TYPES{ $type } = $factory_class;
}
# LAZY LOADING: Allow subclasses to register a type without loading
# its class
my %REGISTERED = ();
# SIMPLE LAZY LOAD: Let the parent know about registered types
sub get_register_map { return \%REGISTERED }
# FLEXIBLE LAZY LOAD: Let the parent know about registered types
sub get_register_type {
my ( $class, $type ) = @_;
return $REGISTERED{ $type };
}
sub set_register_type {
my ( $class, $type, $factory_class ) = @_;
$REGISTERED{ $type } = $factory_class;
}
# Add our default types
# This type is loaded when the statement is run
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
# This type is loaded on the first request for type 'blech'
My::Factory->register_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code -- 'Other::Custom::Class' is
# brought in when 'add_factory_type()' is called
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
# Registering a new factory type in code --
# 'Other::Custom::ClassTwo' in brought in when 'new()' is called
# with type 'custom_two'
My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. For instance, take configuration files. There are
four basic operations you would want to do with any configuration
file: read it in, lookup a value, set a value, write it out. There are
also many different types of configuration files, and you may want
users to be able to provide an implementation for their own home-grown
configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
1;
(Normally you probably would not make your factory the same as your
interface, but this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
My::ConfigFactory->add_factory_type( 'custom' => 'My::CustomConfig' );
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
This might not seem like a very big win, and for small standalone
applications it is not. But when you develop large applications the
C<add_factory_type()> step will almost certainly be done at
application initialization time, hidden away from the eyes of the
application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above, implementation for subclasses is very
simple. The base class defines two methods for subclasses to use:
C<get_factory_class()> and C<add_factory_type()>. Subclasses must
define either C<get_factory_map()> or both C<get_factory_type()> and
C<set_factory_type()>.
=head2 Registering Factory Types
As an additional feature, you can have your class accept registered
types that get brought in only when requested. This lazy loading
feature can be very useful when your factory offers many choices and
users will only need one or two of them at a time, or when some
classes the factory generates use libraries that some users may not
have installed.
For example, say I have a factory that generates an object which
parses GET/POST parameters. One type is straightforward L<CGI|CGI>,
one is L<Apache::Request|Apache::Request>. Many systems do not have
L<Apache::Request|Apache::Request> installed so we do not want to
'use' the module whenever we create the factory.
Instead, we will register these types with the factory and only when
that type is requested will be bring that implementation in. To extend
our example above, we will use the configuration factory:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
my %REGISTERED = ();
sub get_register_map { return \%REGISTERED }
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
1;
We only added two lines. But now we can register configuration types
for modules that the user might not have:
My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
So the C<My::Config::SOAP> class will only get included at the first
request for a configuration object of that type:
my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
{ port => 8080, ... } );
=head1 METHODS
B<new( $type, @params )>
This is a default constructor you can use. It is quite simple:
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
my $self = bless( {}, $class );
return $self->init( @params );
}
We just create a new object of the class associated (from an earlier
call to C<add_factory_type()>) with C<$type> and then call the
C<init()> method of that object. The C<init()> method should return
the object, or die on error.
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>.
Returns: name of class. If a class matching C<$object_type> is not
found, then a C<die()> is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require()>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then a
C<die()> is thrown. A C<warn>ing is issued if the type has already
been added.
B<register_factory_type( $object_type, $object_class )>
Tells the factory to register a new factory type. This type will be
dynamically included (using C<add_factory_type()> at the first request
for an instance of that type.
Returns: name of class registered if successful. If the proper
parameters are not given then a C<die()> is thrown. A C<warn>ing is
issued if the type has already been registered.
=head1 SUBCLASSING
You can do this either the simple way or the flexible way. For most
cases, the simple way will suffice:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
If you want to also add the ability to register classes:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
my %REGISTERED = ();
sub get_register_map { return \%REGISTERED }
If you elect to use the flexible way, you need to implement two
methods:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_class {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_class {
my ( $class, $type, $object_class ) = @_;
return $TYPES{ $type } = $object_class;
}
And if you want to use the flexible way along with registering types:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_class {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_class {
my ( $class, $type, $object_class ) = @_;
return $TYPES{ $type } = $object_class;
}
my %REGISTERED = ();
sub get_register_class {
my ( $class, $type ) = @_;
return $REGISTERED{ $type };
}
sub set_register_class {
my ( $class, $type, $object_class ) = @_;
return $REGISTERED{ $type } = $object_class;
}
How these methods work is entirely up to you -- maybe
C<get_factory_class()> does a lookup in some external resource before
returning the class. Whatever floats your boat.
=head1 USAGE
=head2 Common Pattern
This is a very common pattern. Subclasses create an C<init()>
method that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
my %REGISTERED = ();
sub get_register_map { return \%REGISTERED }
1;
And here is what a subclass might look like:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we've taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
=head2 Registering Types
Many times you will want the parent class to automatically register
the types it knows about:
package My::Factory;
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
my %REGISTERED = ();
sub get_register_map { return \%REGISTERED }
My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
My::Factory->register_factory_type( type2 => 'My::Impl::Type1' );
1;
This allows the default types to be registered when the factory is
initialized. So you can use the default implementations without any
more registering/adding:
#!/usr/bin/perl
use strict;
use My::Factory;
my $impl1 = My::Factory->new( 'type1' );
my $impl2 = My::Factory->new( 'type2' );
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHOR
Chris Winters <[email protected]>
-
-=cut
|
redhotpenguin/Class-Factory | e7299b1c24c1beb0f2cfd44f5125c1ae09af0ef1 | add implementation and docs for registering (lazy loading) factory types | diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index a8d2691..6943a55 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,363 +1,569 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '0.02';
+$Class::Factory::VERSION = '0.03';
# Simple constructor -- override as needed
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
my $self = bless( {}, $class );
return $self->init( @params );
}
# Subclasses should override, but if they don't they shouldn't be
# penalized...
sub init { return $_[0] }
# Find the class associated with $object_type
sub get_factory_class {
my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $map = $item->get_factory_map;
my $factory_class = ( ref $map eq 'HASH' )
? $map->{ $object_type }
: $item->get_factory_type( $object_type );
- unless ( $factory_class ) {
- die "Factory type [$object_type] is not defined in [$class]\n";
+ return $factory_class if ( $factory_class );
+
+ my $register_map = $item->get_register_map;
+ $factory_class = ( ref $register_map eq 'HASH' )
+ ? $register_map->{ $object_type }
+ : $item->get_register_type( $object_type );
+ if ( $factory_class ) {
+ $item->add_factory_type( $object_type, $factory_class );
+ return $factory_class;
}
- return $factory_class;
+ die "Factory type [$object_type] is not defined in [$class]\n";
}
# Associate $object_type with $object_class
sub add_factory_type {
my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
unless ( $object_type ) {
die "Cannot add factory type to [$class]: no type defined\n";
}
unless ( $object_class ) {
die "Cannot add factory type [$object_type] to [$class]: no class defined\n";
}
my $map = $item->get_factory_map;
my $set_object_class = ( ref $map eq 'HASH' )
? $map->{ $object_type }
: $item->get_factory_type( $object_type );
if ( $set_object_class ) {
warn "Attempt to add type [$object_type] to [$class] redundant; ",
"type already exists with class [$set_object_class]\n";
return;
}
eval "require $object_class";
if ( $@ ) {
die "Cannot add factory type [$object_type] to class [$class]: ",
"factory class [$object_class] cannot be required [$@]\n";
}
if ( ref $map eq 'HASH' ) {
$map->{ $object_type } = $object_class;
}
else {
$item->set_factory_type( $object_type, $object_class );
}
return $object_class;
}
+sub register_factory_type {
+ my ( $item, $object_type, $object_class ) = @_;
+ my $class = ref $item || $item;
+ unless ( $object_type ) {
+ die "Cannot add factory type to [$class]: no type defined\n";
+ }
+ unless ( $object_class ) {
+ die "Cannot add factory type [$object_type] to [$class]: no class defined\n";
+ }
+
+ my $map = $item->get_register_map;
+ my $set_object_class = ( ref $map eq 'HASH' )
+ ? $map->{ $object_type }
+ : $item->get_register_type( $object_type );
+ if ( $set_object_class ) {
+ warn "Attempt to register type [$object_type] with [$class] is",
+ "redundant; type registered with class [$set_object_class]\n";
+ return;
+ }
+ if ( ref $map eq 'HASH' ) {
+ $map->{ $object_type } = $object_class;
+ }
+ else {
+ $item->set_register_type( $object_type, $object_class );
+ }
+}
+
########################################
# INTERFACE
# We don't die when these are called because the subclass can define
# either A + B or C
-sub get_factory_type { return undef }
-sub set_factory_type { return undef }
-sub get_factory_map { return undef }
+sub get_factory_type { return undef }
+sub set_factory_type { return undef }
+sub get_factory_map { return undef }
+sub get_register_type { return undef }
+sub set_register_type { return undef }
+sub get_register_map { return undef }
1;
__END__
=pod
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
# SIMPLE: Let the parent know about our types
sub get_factory_map { return \%TYPES }
# FLEXIBLE: Let the parent know about our types
sub get_factory_type {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_type {
my ( $class, $type, $factory_class ) = @_;
$TYPES{ $type } = $factory_class;
}
+ # LAZY LOADING: Allow subclasses to register a type without loading
+ # its class
+
+ my %REGISTERED = ();
+
+ # SIMPLE LAZY LOAD: Let the parent know about registered types
+
+ sub get_register_map { return \%REGISTERED }
+
+ # FLEXIBLE LAZY LOAD: Let the parent know about registered types
+
+ sub get_register_type {
+ my ( $class, $type ) = @_;
+ return $REGISTERED{ $type };
+ }
+
+ sub set_register_type {
+ my ( $class, $type, $factory_class ) = @_;
+ $REGISTERED{ $type } = $factory_class;
+ }
+
+
# Add our default types
+ # This type is loaded when the statement is run
+
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
- My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
+
+ # This type is loaded on the first request for type 'blech'
+
+ My::Factory->register_factory_type( blech => 'My::Factory::Blech' );
1;
- # Adding a new factory type in code
+ # Adding a new factory type in code -- 'Other::Custom::Class' is
+ # brought in when 'add_factory_type()' is called
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
+ # Registering a new factory type in code --
+ # 'Other::Custom::ClassTwo' in brought in when 'new()' is called
+ # with type 'custom_two'
+
+ My::Factory->register_factory_type( custom_two => 'Other::Custom::ClassTwo' );
+ my $custom_object = My::Factory->new( 'custom_two', { this => 'that' } );
+
+
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. For instance, take configuration files. There are
four basic operations you would want to do with any configuration
file: read it in, lookup a value, set a value, write it out. There are
also many different types of configuration files, and you may want
users to be able to provide an implementation for their own home-grown
configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer. C<Class::Factory> even provides a simple
constructor for you:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
1;
(Normally you probably would not make your factory the same as your
interface, but this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
My::ConfigFactory->add_factory_type( 'custom' => 'My::CustomConfig' );
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
This might not seem like a very big win, and for small standalone
applications it is not. But when you develop large applications the
C<add_factory_type()> step will almost certainly be done at
application initialization time, hidden away from the eyes of the
application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above, implementation for subclasses is very
simple. The base class defines two methods for subclasses to use:
C<get_factory_class()> and C<add_factory_type()>. Subclasses must
define either C<get_factory_map()> or both C<get_factory_type()> and
C<set_factory_type()>.
+=head2 Registering Factory Types
+
+As an additional feature, you can have your class accept registered
+types that get brought in only when requested. This lazy loading
+feature can be very useful when your factory offers many choices and
+users will only need one or two of them at a time, or when some
+classes the factory generates use libraries that some users may not
+have installed.
+
+For example, say I have a factory that generates an object which
+parses GET/POST parameters. One type is straightforward L<CGI|CGI>,
+one is L<Apache::Request|Apache::Request>. Many systems do not have
+L<Apache::Request|Apache::Request> installed so we do not want to
+'use' the module whenever we create the factory.
+
+Instead, we will register these types with the factory and only when
+that type is requested will be bring that implementation in. To extend
+our example above, we will use the configuration factory:
+
+ package My::ConfigFactory;
+
+ use strict;
+ use base qw( Class::Factory );
+
+ my %TYPES = ();
+ sub get_factory_map { return \%TYPES }
+ my %REGISTERED = ();
+ sub get_register_map { return \%REGISTERED }
+
+ sub read { die "Define read() in implementation" }
+ sub write { die "Define write() in implementation" }
+ sub get { die "Define get() in implementation" }
+ sub set { die "Define set() in implementation" }
+
+ 1;
+
+We only added two lines. But now we can register configuration types
+for modules that the user might not have:
+
+ My::ConfigFactory->register_factory_type( SOAP => 'My::Config::SOAP' );
+
+So the C<My::Config::SOAP> class will only get included at the first
+request for a configuration object of that type:
+
+ my $config = My::ConfigFactory->new( 'SOAP', 'http://myco.com/',
+ { port => 8080, ... } );
+
=head1 METHODS
B<new( $type, @params )>
This is a default constructor you can use. It is quite simple:
sub new {
my ( $pkg, $type, @params ) = @_;
my $class = $pkg->get_factory_class( $type );
my $self = bless( {}, $class );
return $self->init( @params );
}
We just create a new object of the class associated (from an earlier
call to C<add_factory_type()>) with C<$type> and then call the
C<init()> method of that object. The C<init()> method should return
the object, or die on error.
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>.
Returns: name of class. If a class matching C<$object_type> is not
found, then a C<die()> is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require()>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then a
-C<die()> is thrown.
+C<die()> is thrown. A C<warn>ing is issued if the type has already
+been added.
+
+B<register_factory_type( $object_type, $object_class )>
+
+Tells the factory to register a new factory type. This type will be
+dynamically included (using C<add_factory_type()> at the first request
+for an instance of that type.
+
+Returns: name of class registered if successful. If the proper
+parameters are not given then a C<die()> is thrown. A C<warn>ing is
+issued if the type has already been registered.
=head1 SUBCLASSING
You can do this either the simple way or the flexible way. For most
cases, the simple way will suffice:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
+If you want to also add the ability to register classes:
+
+ package My::Factory;
+
+ use base qw( Class::Factory );
+
+ my %TYPES = ();
+ sub get_factory_map { return \%TYPES }
+ my %REGISTERED = ();
+ sub get_register_map { return \%REGISTERED }
+
+
If you elect to use the flexible way, you need to implement two
methods:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_class {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_class {
my ( $class, $type, $object_class ) = @_;
return $TYPES{ $type } = $object_class;
}
+And if you want to use the flexible way along with registering types:
+
+ package My::Factory;
+
+ use base qw( Class::Factory );
+
+ my %TYPES = ();
+ sub get_factory_class {
+ my ( $class, $type ) = @_;
+ return $TYPES{ $type };
+ }
+
+ sub set_factory_class {
+ my ( $class, $type, $object_class ) = @_;
+ return $TYPES{ $type } = $object_class;
+ }
+
+ my %REGISTERED = ();
+ sub get_register_class {
+ my ( $class, $type ) = @_;
+ return $REGISTERED{ $type };
+ }
+
+ sub set_register_class {
+ my ( $class, $type, $object_class ) = @_;
+ return $REGISTERED{ $type } = $object_class;
+ }
+
+
How these methods work is entirely up to you -- maybe
C<get_factory_class()> does a lookup in some external resource before
returning the class. Whatever floats your boat.
=head1 USAGE
=head2 Common Pattern
This is a very common pattern. Subclasses create an C<init()>
method that gets called when the object is created:
package My::Factory;
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
+ my %REGISTERED = ();
+ sub get_register_map { return \%REGISTERED }
1;
And here is what a subclass might look like:
package My::Subclass;
use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we've taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
The parent class (C<My::Factory>) has made as part of its definition
that the only parameters to be passed to the C<init()> method are
C<$filename> and C<$params>, in that order. It could just as easily
have specified a single hashref parameter.
These sorts of specifications are informal and not enforced by this
C<Class::Factory>.
+=head2 Registering Types
+
+Many times you will want the parent class to automatically register
+the types it knows about:
+
+ package My::Factory;
+
+ use strict;
+ use base qw( Class::Factory );
+
+ my %TYPES = ();
+ sub get_factory_map { return \%TYPES }
+ my %REGISTERED = ();
+ sub get_register_map { return \%REGISTERED }
+
+ My::Factory->register_factory_type( type1 => 'My::Impl::Type1' );
+ My::Factory->register_factory_type( type2 => 'My::Impl::Type1' );
+
+ 1;
+
+This allows the default types to be registered when the factory is
+initialized. So you can use the default implementations without any
+more registering/adding:
+
+ #!/usr/bin/perl
+
+ use strict;
+ use My::Factory;
+
+ my $impl1 = My::Factory->new( 'type1' );
+ my $impl2 = My::Factory->new( 'type2' );
+
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHOR
Chris Winters <[email protected]>
=cut
|
redhotpenguin/Class-Factory | 5e3f6d070d4f45386f3bdbeaabb3383555d50579 | add changes | diff --git a/Changes b/Changes
index 11b3aba..4c66709 100644
--- a/Changes
+++ b/Changes
@@ -1,14 +1,22 @@
Revision history for Perl extension Class::Factory.
+0.03 Sun Feb 10 13:00:20 EST 2002
+
+ Added the ability to register a type/class without having
+ Class::Factory include it. This is useful for modules that want
+ to know all of their types at startup time but don't want to
+ bring in a particular class until that type is requested. (See
+ POD for details.)
+
0.02 Wed Jan 30 00:22:58 EST 2002
Added simple constructor to be inherited as needed. This
constructor automatically calls 'init()', not coincidentally the
name that Class::Base uses. Small variable name changes.
0.01 Mon Jan 28 08:35:09 EST 2002
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
|
redhotpenguin/Class-Factory | 773c61aaae88f1df9aca261f419a7a446c172066 | added register methods as well | diff --git a/t/MyFlexibleBand.pm b/t/MyFlexibleBand.pm
index 25dce22..597372e 100644
--- a/t/MyFlexibleBand.pm
+++ b/t/MyFlexibleBand.pm
@@ -1,35 +1,39 @@
package MyFlexibleBand;
# $Id$
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_type { return $TYPES{ $_[1] } }
sub set_factory_type { return $TYPES{ $_[1] } = $_[2] }
+my %REGISTER = ();
+sub get_register_type { return $REGISTER{ $_[1] } }
+sub set_register_type { return $REGISTER{ $_[1] } = $_[2] }
+
sub init {
my ( $self, $params ) = @_;
$self->band_name( $params->{band_name} );
return $self;
}
sub band_name {
my ( $self, $name ) = @_;
$self->{band_name} = $name if ( $name );
return $self->{band_name};
}
sub genre {
my ( $self, $genre ) = @_;
$self->{genre} = $genre if ( $genre );
return $self->{genre};
}
MyFlexibleBand->add_factory_type( rock => 'MyRockBand' );
-MyFlexibleBand->add_factory_type( country => 'MyCountryBand' );
+MyFlexibleBand->register_factory_type( country => 'MyCountryBand' );
1;
diff --git a/t/MySimpleBand.pm b/t/MySimpleBand.pm
index f7c0920..d9f83e1 100644
--- a/t/MySimpleBand.pm
+++ b/t/MySimpleBand.pm
@@ -1,37 +1,39 @@
package MySimpleBand;
# $Id$
use strict;
use base qw( Class::Factory );
#use Class::Factory;
#@MySimpleBand::ISA = qw( Class::Factory );
-my %TYPES = ();
-sub get_factory_map { return \%TYPES }
+my %TYPES = ();
+my %REGISTER = ();
+sub get_factory_map { return \%TYPES }
+sub get_register_map { return \%REGISTER }
sub init {
my ( $self, $params ) = @_;
$self->band_name( $params->{band_name} );
return $self;
}
sub band_name {
my ( $self, $name ) = @_;
$self->{band_name} = $name if ( $name );
return $self->{band_name};
}
sub genre {
my ( $self, $genre ) = @_;
$self->{genre} = $genre if ( $genre );
return $self->{genre};
}
MySimpleBand->add_factory_type( rock => 'MyRockBand' );
-MySimpleBand->add_factory_type( country => 'MyCountryBand' );
+MySimpleBand->register_factory_type( country => 'MyCountryBand' );
1;
|
redhotpenguin/Class-Factory | 22847c263b6e28bd8557633f3811fb9abd523416 | modified test so we can see how the new register stuff works | diff --git a/t/factory.t b/t/factory.t
index 716d288..c92ac7e 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,64 +1,68 @@
# -*-perl-*-
use strict;
-use Test::More tests => 21;
+use Test::More tests => 23;
use lib qw( ./t ./lib );
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
- my $map = MySimpleBand->get_factory_map;
- is( ref( $map ), 'HASH', 'Return of get_factory_map()' );
- is( scalar keys %{ $map }, 2, 'Keys in map' );
- is( $map->{rock}, 'MyRockBand', 'Simple type added 1' );
- is( $map->{country}, 'MyCountryBand', 'Simple type added 2' );
+ my $factory_map = MySimpleBand->get_factory_map;
+ is( ref( $factory_map ), 'HASH', 'Return of get_factory_map()' );
+ is( scalar keys %{ $factory_map }, 1, 'Keys in factory map' );
+ is( $factory_map->{rock}, 'MyRockBand', 'Simple type added' );
+
+ my $register_map = MySimpleBand->get_register_map;
+ is( ref( $register_map ), 'HASH', 'Return of get_register_map()' );
+ is( scalar keys %{ $register_map }, 1, 'Keys in register map' );
+ is( $register_map->{country}, 'MyCountryBand', 'Simple type registered' );
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
- is( ref( $rock ), 'MyRockBand', 'Simple object returned 1' );
- is( $rock->band_name(), $rock_band, 'Simple object super init parameter set 1' );
- is( $rock->genre(), $rock_genre, 'Simple object self init parameter set 1' );
+ is( ref( $rock ), 'MyRockBand', 'Simple added object returned' );
+ is( $rock->band_name(), $rock_band, 'Simple added super init parameter set' );
+ is( $rock->genre(), $rock_genre, 'Simple added self init parameter set' );
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
- is( ref( $country ), 'MyCountryBand', 'Simple object returned 2' );
- is( $country->band_name(), $country_band, 'Simple object super init parameter set 2' );
- is( $country->genre(), $country_genre, 'Simple object self init parameter set 2' );
+ is( ref( $country ), 'MyCountryBand', 'Simple registered object returned' );
+ is( $country->band_name(), $country_band, 'Simple registered object super init parameter set' );
+ is( $country->genre(), $country_genre, 'Simple registered object self init parameter set' );
}
# Next the flexible settting
{
require_ok( 'MyFlexibleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MyFlexibleBand );
@MyCountryBand::ISA = qw( MyFlexibleBand );
- is( MyFlexibleBand->get_factory_type( 'rock' ), 'MyRockBand', 'Flexible type added 1' );
- is( MyFlexibleBand->get_factory_type( 'country' ), 'MyCountryBand', 'Flexible type added 2' );
+ is( MyFlexibleBand->get_factory_type( 'rock' ), 'MyRockBand', 'Flexible type added' );
+ is( MyFlexibleBand->get_register_type( 'country' ), 'MyCountryBand', 'Flexible type registered' );
my $rock = MyFlexibleBand->new( 'rock', { band_name => $rock_band } );
- is( ref( $rock ), 'MyRockBand', 'Flexible object returned 1' );
- is( $rock->band_name(), $rock_band, 'Flexible object super init parameter set 1' );
- is( $rock->genre(), $rock_genre, 'Flexible object self init parameter set 1' );
+ is( ref( $rock ), 'MyRockBand', 'Flexible added object returned' );
+ is( $rock->band_name(), $rock_band, 'Flexible added object super init parameter set' );
+ is( $rock->genre(), $rock_genre, 'Flexible added object self init parameter set' );
my $country = MyFlexibleBand->new( 'country', { band_name => $country_band } );
- is( ref( $country ), 'MyCountryBand', 'Flexible object returned 2' );
- is( $country->band_name(), $country_band, 'Flexible object super init parameter set 2' );
- is( $country->genre(), $country_genre, 'Flexible object self init parameter set 2' );
+ is( ref( $country ), 'MyCountryBand', 'Flexible registered object returned' );
+ is( $country->band_name(), $country_band, 'Flexible registered object super init parameter set' );
+ is( $country->genre(), $country_genre, 'Flexible registered object self init parameter set' );
}
|
redhotpenguin/Class-Factory | 6d51506c125e45fd1fecaebe9a33f1c2b3328a1f | add dist | diff --git a/dist/Class-Factory-0.02.tar.gz b/dist/Class-Factory-0.02.tar.gz
new file mode 100644
index 0000000..7364b41
Binary files /dev/null and b/dist/Class-Factory-0.02.tar.gz differ
|
redhotpenguin/Class-Factory | d343b5dfa5e21d964cb6ff0772fe27dfcbc0edc9 | track changes | diff --git a/Changes b/Changes
index 9be878d..11b3aba 100644
--- a/Changes
+++ b/Changes
@@ -1,8 +1,14 @@
Revision history for Perl extension Class::Factory.
-0.01 Mon Jan 28 08:35:09 2002
+0.02 Wed Jan 30 00:22:58 EST 2002
+
+ Added simple constructor to be inherited as needed. This
+ constructor automatically calls 'init()', not coincidentally the
+ name that Class::Base uses. Small variable name changes.
+
+0.01 Mon Jan 28 08:35:09 EST 2002
Original version with tests, documentation and everything,
written after the third or fourth time I cut-and-pasted a
'add_type()' method to implement a dynamic factory class :-)
|
redhotpenguin/Class-Factory | 279ade0ba121d0f27398bb1275ea71d425942431 | inherit new() | diff --git a/t/MyCountryBand.pm b/t/MyCountryBand.pm
index 0652541..cfc5763 100644
--- a/t/MyCountryBand.pm
+++ b/t/MyCountryBand.pm
@@ -1,14 +1,14 @@
package MyCountryBand;
use strict;
# Note: @ISA is modified during the test
-sub initialize {
+sub init {
my ( $self, $params ) = @_;
- $self->SUPER::initialize( $params );
+ $self->SUPER::init( $params );
$self->genre( 'COUNTRY' );
return $self;
}
1;
diff --git a/t/MyFlexibleBand.pm b/t/MyFlexibleBand.pm
index 0a6c5ed..25dce22 100644
--- a/t/MyFlexibleBand.pm
+++ b/t/MyFlexibleBand.pm
@@ -1,43 +1,35 @@
package MyFlexibleBand;
# $Id$
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_type { return $TYPES{ $_[1] } }
sub set_factory_type { return $TYPES{ $_[1] } = $_[2] }
-sub new {
- my ( $class, $type, $params ) = @_;
- my $factory_class = $class->get_factory_class( $type );
- my $self = bless( {}, $factory_class );
- return $self->initialize( $params );
-}
-
-
-sub initialize {
+sub init {
my ( $self, $params ) = @_;
$self->band_name( $params->{band_name} );
return $self;
}
sub band_name {
my ( $self, $name ) = @_;
$self->{band_name} = $name if ( $name );
return $self->{band_name};
}
sub genre {
my ( $self, $genre ) = @_;
$self->{genre} = $genre if ( $genre );
return $self->{genre};
}
MyFlexibleBand->add_factory_type( rock => 'MyRockBand' );
MyFlexibleBand->add_factory_type( country => 'MyCountryBand' );
1;
diff --git a/t/MyRockBand.pm b/t/MyRockBand.pm
index 274627c..7159787 100644
--- a/t/MyRockBand.pm
+++ b/t/MyRockBand.pm
@@ -1,14 +1,14 @@
package MyRockBand;
use strict;
# Note: @ISA is modified during the test
-sub initialize {
+sub init {
my ( $self, $params ) = @_;
- $self->SUPER::initialize( $params );
+ $self->SUPER::init( $params );
$self->genre( 'ROCK' );
return $self;
}
1;
diff --git a/t/MySimpleBand.pm b/t/MySimpleBand.pm
index 1ea95d8..f7c0920 100644
--- a/t/MySimpleBand.pm
+++ b/t/MySimpleBand.pm
@@ -1,45 +1,37 @@
package MySimpleBand;
# $Id$
use strict;
use base qw( Class::Factory );
#use Class::Factory;
#@MySimpleBand::ISA = qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
-sub new {
- my ( $class, $type, $params ) = @_;
- my $factory_class = $class->get_factory_class( $type );
- my $self = bless( {}, $factory_class );
- return $self->initialize( $params );
-}
-
-
-sub initialize {
+sub init {
my ( $self, $params ) = @_;
$self->band_name( $params->{band_name} );
return $self;
}
sub band_name {
my ( $self, $name ) = @_;
$self->{band_name} = $name if ( $name );
return $self->{band_name};
}
sub genre {
my ( $self, $genre ) = @_;
$self->{genre} = $genre if ( $genre );
return $self->{genre};
}
MySimpleBand->add_factory_type( rock => 'MyRockBand' );
MySimpleBand->add_factory_type( country => 'MyCountryBand' );
1;
|
redhotpenguin/Class-Factory | 6770597b099b76fbb2c6bb02fbfaf8a265366cd4 | add a new() method that can be inherited; variable name changes | diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index fb700b3..a8d2691 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,340 +1,363 @@
package Class::Factory;
# $Id$
use strict;
-$Class::Factory::VERSION = '0.01';
+$Class::Factory::VERSION = '0.02';
+# Simple constructor -- override as needed
+
+sub new {
+ my ( $pkg, $type, @params ) = @_;
+ my $class = $pkg->get_factory_class( $type );
+ my $self = bless( {}, $class );
+ return $self->init( @params );
+}
+
+
+# Subclasses should override, but if they don't they shouldn't be
+# penalized...
+
+sub init { return $_[0] }
+
+# Find the class associated with $object_type
sub get_factory_class {
- my ( $item, $factory_type ) = @_;
+ my ( $item, $object_type ) = @_;
my $class = ref $item || $item;
my $map = $item->get_factory_map;
my $factory_class = ( ref $map eq 'HASH' )
- ? $map->{ $factory_type }
- : $item->get_factory_type( $factory_type );
+ ? $map->{ $object_type }
+ : $item->get_factory_type( $object_type );
unless ( $factory_class ) {
- die "Factory type [$factory_type] is not defined in [$class]\n";
+ die "Factory type [$object_type] is not defined in [$class]\n";
}
return $factory_class;
}
+# Associate $object_type with $object_class
+
sub add_factory_type {
- my ( $item, $factory_type, $factory_class ) = @_;
+ my ( $item, $object_type, $object_class ) = @_;
my $class = ref $item || $item;
- unless ( $factory_type ) {
+ unless ( $object_type ) {
die "Cannot add factory type to [$class]: no type defined\n";
}
- unless ( $factory_class ) {
- die "Cannot add factory type [$factory_type] to [$class]: no class defined\n";
+ unless ( $object_class ) {
+ die "Cannot add factory type [$object_type] to [$class]: no class defined\n";
}
my $map = $item->get_factory_map;
- my $set_factory_class = ( ref $map eq 'HASH' )
- ? $map->{ $factory_type }
- : $item->get_factory_type( $factory_type );
- if ( $set_factory_class ) {
- warn "Attempt to add type [$factory_type] to [$class] redundant; ",
- "type already exists with class [$set_factory_class]\n";
+ my $set_object_class = ( ref $map eq 'HASH' )
+ ? $map->{ $object_type }
+ : $item->get_factory_type( $object_type );
+ if ( $set_object_class ) {
+ warn "Attempt to add type [$object_type] to [$class] redundant; ",
+ "type already exists with class [$set_object_class]\n";
return;
}
- eval "require $factory_class";
+ eval "require $object_class";
if ( $@ ) {
- die "Cannot add factory type [$factory_type] to class [$class]: ",
- "factory class [$factory_class] cannot be required [$@]\n";
+ die "Cannot add factory type [$object_type] to class [$class]: ",
+ "factory class [$object_class] cannot be required [$@]\n";
}
if ( ref $map eq 'HASH' ) {
- $map->{ $factory_type } = $factory_class;
+ $map->{ $object_type } = $object_class;
}
else {
- $item->set_factory_type( $factory_type, $factory_class );
+ $item->set_factory_type( $object_type, $object_class );
}
- return $factory_class;
+ return $object_class;
}
########################################
# INTERFACE
# We don't die when these are called because the subclass can define
# either A + B or C
sub get_factory_type { return undef }
sub set_factory_type { return undef }
sub get_factory_map { return undef }
1;
__END__
=pod
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
# SIMPLE: Let the parent know about our types
sub get_factory_map { return \%TYPES }
# FLEXIBLE: Let the parent know about our types
sub get_factory_type {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_type {
my ( $class, $type, $factory_class ) = @_;
$TYPES{ $type } = $factory_class;
}
- # Simple factory constructor
-
- sub new {
- my ( $class, $type, $params ) = @_;
- my $factory_class = $class->get_factory_class( $type );
- return bless( $params, $factory_class );
- }
-
# Add our default types
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. For instance, take configuration files. There are
four basic operations you would want to do with any configuration
file: read it in, lookup a value, set a value, write it out. There are
also many different types of configuration files, and you may want
users to be able to provide an implementation for their own home-grown
configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
-configuration serializer:
+configuration serializer. C<Class::Factory> even provides a simple
+constructor for you:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
- sub new {
- my ( $class, $type, $filename, @params ) = @_;
- my $factory_class = $class->get_factory_class( $type );
- my $self = bless( {}, $factory_class );
- return $self->initialize( $filename, @params );
- }
-
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
- sub initialize {
+ sub init {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
1;
(Normally you probably would not make your factory the same as your
interface, but this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
My::ConfigFactory->add_factory_type( 'custom' => 'My::CustomConfig' );
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
This might not seem like a very big win, and for small standalone
applications it is not. But when you develop large applications the
C<add_factory_type()> step will almost certainly be done at
application initialization time, hidden away from the eyes of the
application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above, implementation for subclasses is very
simple. The base class defines two methods for subclasses to use:
C<get_factory_class()> and C<add_factory_type()>. Subclasses must
define either C<get_factory_map()> or both C<get_factory_type()> and
C<set_factory_type()>.
=head1 METHODS
+B<new( $type, @params )>
+
+This is a default constructor you can use. It is quite simple:
+
+ sub new {
+ my ( $pkg, $type, @params ) = @_;
+ my $class = $pkg->get_factory_class( $type );
+ my $self = bless( {}, $class );
+ return $self->init( @params );
+ }
+
+We just create a new object of the class associated (from an earlier
+call to C<add_factory_type()>) with C<$type> and then call the
+C<init()> method of that object. The C<init()> method should return
+the object, or die on error.
+
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>.
Returns: name of class. If a class matching C<$object_type> is not
found, then a C<die()> is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require()>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then a
C<die()> is thrown.
=head1 SUBCLASSING
You can do this either the simple way or the flexible way. For most
cases, the simple way will suffice:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
If you elect to use the flexible way, you need to implement two
methods:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_class {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_class {
my ( $class, $type, $object_class ) = @_;
return $TYPES{ $type } = $object_class;
}
How these methods work is entirely up to you -- maybe
C<get_factory_class()> does a lookup in some external resource before
returning the class. Whatever floats your boat.
=head1 USAGE
=head2 Common Pattern
-This is a very common pattern. Subclasses create an C<initialize()>
+This is a very common pattern. Subclasses create an C<init()>
method that gets called when the object is created:
package My::Factory;
+ use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
- sub new {
- my ( $class, $type, @params ) = @_;
- my $object_class = $class->get_factory_class( $type );
- my $self = bless( {}, $object_class );
- return $self->initialize( @params );
- }
-
1;
And here is what a subclass might look like:
package My::Subclass;
+ use strict;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we've taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
- sub initialize {
+ sub init {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
+The parent class (C<My::Factory>) has made as part of its definition
+that the only parameters to be passed to the C<init()> method are
+C<$filename> and C<$params>, in that order. It could just as easily
+have specified a single hashref parameter.
+
+These sorts of specifications are informal and not enforced by this
+C<Class::Factory>.
+
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern, pp. 107-116.
=head1 AUTHOR
Chris Winters <[email protected]>
=cut
|
redhotpenguin/Class-Factory | 920bc6df13ae9d3461e25071d82dcc7e23326cac | add first release | diff --git a/dist/Class-Factory-0.01.tar.gz b/dist/Class-Factory-0.01.tar.gz
new file mode 100644
index 0000000..c007656
Binary files /dev/null and b/dist/Class-Factory-0.01.tar.gz differ
|
redhotpenguin/Class-Factory | 34443bb38695b94b8f4d9733c83909fc925ff4a4 | cosmetic | diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index ab7844c..d860cbf 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,335 +1,337 @@
package Class::Factory;
# $Id$
use strict;
$Class::Factory::VERSION = '0.01';
sub get_factory_class {
my ( $item, $factory_type ) = @_;
my $class = ref $item || $item;
my $map = $item->get_factory_map;
my $factory_class = ( ref $map eq 'HASH' )
? $map->{ $factory_type }
: $item->get_factory_type( $factory_type );
unless ( $factory_class ) {
die "Factory type [$factory_type] is not defined in [$class]\n";
}
return $factory_class;
}
sub add_factory_type {
my ( $item, $factory_type, $factory_class ) = @_;
my $class = ref $item || $item;
unless ( $factory_type ) {
die "Cannot add factory type to [$class]: no type defined\n";
}
unless ( $factory_class ) {
die "Cannot add factory type [$factory_type] to [$class]: no class defined\n";
}
my $map = $item->get_factory_map;
my $set_factory_class = ( ref $map eq 'HASH' )
? $map->{ $factory_type }
: $item->get_factory_type( $factory_type );
if ( $set_factory_class ) {
warn "Attempt to add type [$factory_type] to [$class] redundant; ",
"type already exists with class [$set_factory_class]\n";
return;
}
eval "require $factory_class";
if ( $@ ) {
die "Cannot add factory type [$factory_type] to class [$class]: ",
"factory class [$factory_class] cannot be required [$@]\n";
}
if ( ref $map eq 'HASH' ) {
$map->{ $factory_type } = $factory_class;
}
else {
$item->set_factory_type( $factory_type, $factory_class );
}
return $factory_class;
}
########################################
# INTERFACE
# We don't die when these are called because the subclass can define
# either A + B or C
sub get_factory_type { return undef }
sub set_factory_type { return undef }
sub get_factory_map { return undef }
1;
__END__
+=pod
+
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub new {
my ( $class, $type, $params ) = @_;
my $factory_class = $class->get_factory_class( $type );
return bless( $params, $factory_class );
}
# SIMPLE: Let the parent know about our types
sub get_factory_map { return \%TYPES }
# FLEXIBLE: Let the parent know about our types
sub get_factory_type {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_type {
my ( $class, $type, $factory_class ) = @_;
$TYPES{ $type } = $factory_class;
}
# Add our default types
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. For instance, take configuration files. There are
four basic operations you would want to do with any configuration
file: read it in, lookup a value, set a value, write it out. There are
also many different types of configuration files, and you may want
users to be able to provide an implementation for their own home-grown
configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
sub new {
my ( $class, $type, $filename, @params ) = @_;
my $factory_class = $class->get_factory_class( $type );
my $self = bless( {}, $factory_class );
return $self->initialize( $filename, @params );
}
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub initialize {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
1;
(Normally you probably would not make your factory the same as your
interface, but this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
My::ConfigFactory->add_factory_type( 'custom' => 'My::CustomConfig' );
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
This might not seem like a very big win, and for small standalone
applications it is not. But when you develop large applications the
C<add_factory_type()> step will almost certainly be done at
application initialization time, hidden away from the eyes of the
application developer. That developer will only know that she can
access the different object types as if they are part of the system.
As you see in the example above, implementation for subclasses is very
simple. The base class defines two methods for subclasses to use:
C<get_factory_class()> and C<add_factory_type()>. Subclasses must
define either C<get_factory_map()> or both C<get_factory_type()> and
C<set_factory_type()>.
=head1 METHODS
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>.
Returns: name of class. If a class matching C<$object_type> is not
found, then a C<die()> is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require()>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then a
C<die()> is thrown.
=head1 SUBCLASSING
You can do this either the simple way or the flexible way. For most
cases, the simple way will suffice:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
If you elect to use the flexible way, you need to implement two
methods:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_class {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_class {
my ( $class, $type, $object_class ) = @_;
return $TYPES{ $type } = $object_class;
}
How these methods work is entirely up to you -- maybe
C<get_factory_class()> does a lookup in some external resource before
returning the class. Whatever floats your boat.
=head1 USAGE
=head2 Common Pattern
This is a very common pattern. Subclasses create an C<initialize()>
method that gets called when the object is created:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
sub new {
my ( $class, $type, @params ) = @_;
my $object_class = $class->get_factory_class( $type );
my $self = bless( {}, $object_class );
return $self->initialize( @params );
}
1;
And here is what a subclass might look like:
package My::Subclass;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we've taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub initialize {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern at pp. 107-116.
=head1 AUTHOR
Chris Winters <[email protected]>
=cut
|
redhotpenguin/Class-Factory | fc3aa3886db9e9356e06b3eaafb8605853e1af82 | created from synopsis | diff --git a/README b/README
index 5f577c1..81764e8 100644
--- a/README
+++ b/README
@@ -1,35 +1,68 @@
-Class/Factory version 0.01
+Class::Factory - Base class for dynamic factory classes.
==========================
-The README is used to introduce the module and provide instructions on
-how to install the module, any machine dependencies it may have (for
-example C compilers and installed libraries) and any other information
-that should be provided before the module is installed.
+ package My::Factory;
-A README file is required for CPAN modules since CPAN extracts the
-README file from a module distribution so that people browsing the
-archive can use it get an idea of the modules uses. It is usually a
-good idea to provide version information here so that people can
-decide whether fixes for the module are worth downloading.
+ use base qw( Class::Factory );
+
+ my %TYPES = ();
+
+ sub new {
+ my ( $class, $type, $params ) = @_;
+ my $factory_class = $class->get_factory_class( $type );
+ return bless( $params, $factory_class );
+ }
+
+ # SIMPLE: Let the parent know about our types
+
+ sub get_factory_map { return \%TYPES }
+
+ # FLEXIBLE: Let the parent know about our types
+
+ sub get_factory_type {
+ my ( $class, $type ) = @_;
+ return $TYPES{ $type };
+ }
+
+ sub set_factory_type {
+ my ( $class, $type, $factory_class ) = @_;
+ $TYPES{ $type } = $factory_class;
+ }
+
+ # Add our default types
+
+ My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
+ My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
+
+ 1;
+
+ # Adding a new factory type in code
+
+ My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
+ my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
+
+See POD for details
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:
-
- blah blah blah
+None
COPYRIGHT AND LICENCE
-Put the correct copyright and licence information here.
+Copyright (c) 2002 Chris Winters. All rights reserved.
+
+This library is free software; you can redistribute it and/or modify
+it under the same terms as Perl itself.
-Copyright (C) 2002 A. U. Thor blah blah blah
+AUTHOR
+Chris Winters <[email protected]>
\ No newline at end of file
|
redhotpenguin/Class-Factory | ed6de933f30781d306e6e78ea8970575c3de7e77 | marked down original changes | diff --git a/Changes b/Changes
index db6a14d..9be878d 100644
--- a/Changes
+++ b/Changes
@@ -1,6 +1,8 @@
Revision history for Perl extension Class::Factory.
0.01 Mon Jan 28 08:35:09 2002
- - original version; created by h2xs 1.21 with options
- -A -X -n Class::Factory
+
+ Original version with tests, documentation and everything,
+ written after the third or fourth time I cut-and-pasted a
+ 'add_type()' method to implement a dynamic factory class :-)
|
redhotpenguin/Class-Factory | 8135e7689dd62c0c15ae33eec06598a1e756f68d | add lib/ to lib path | diff --git a/t/factory.t b/t/factory.t
index b3c8cef..716d288 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,64 +1,64 @@
# -*-perl-*-
use strict;
use Test::More tests => 21;
-use lib qw( t );
+use lib qw( ./t ./lib );
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
my $map = MySimpleBand->get_factory_map;
is( ref( $map ), 'HASH', 'Return of get_factory_map()' );
is( scalar keys %{ $map }, 2, 'Keys in map' );
is( $map->{rock}, 'MyRockBand', 'Simple type added 1' );
is( $map->{country}, 'MyCountryBand', 'Simple type added 2' );
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Simple object returned 1' );
is( $rock->band_name(), $rock_band, 'Simple object super init parameter set 1' );
is( $rock->genre(), $rock_genre, 'Simple object self init parameter set 1' );
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Simple object returned 2' );
is( $country->band_name(), $country_band, 'Simple object super init parameter set 2' );
is( $country->genre(), $country_genre, 'Simple object self init parameter set 2' );
}
# Next the flexible settting
{
require_ok( 'MyFlexibleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MyFlexibleBand );
@MyCountryBand::ISA = qw( MyFlexibleBand );
is( MyFlexibleBand->get_factory_type( 'rock' ), 'MyRockBand', 'Flexible type added 1' );
is( MyFlexibleBand->get_factory_type( 'country' ), 'MyCountryBand', 'Flexible type added 2' );
my $rock = MyFlexibleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Flexible object returned 1' );
is( $rock->band_name(), $rock_band, 'Flexible object super init parameter set 1' );
is( $rock->genre(), $rock_genre, 'Flexible object self init parameter set 1' );
my $country = MyFlexibleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Flexible object returned 2' );
is( $country->band_name(), $country_band, 'Flexible object super init parameter set 2' );
is( $country->genre(), $country_genre, 'Flexible object self init parameter set 2' );
}
|
redhotpenguin/Class-Factory | b294ea65cc16cfd4e3355e81cc49e5c547e84018 | added testing files/modules | diff --git a/MANIFEST b/MANIFEST
index 70c8250..b4548ac 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,6 +1,11 @@
Changes
-Factory.pm
Makefile.PL
MANIFEST
README
-test.pl
+lib/Class/Factory.pm
+t/factory.t
+t/MyCountryBand.pm
+t/MyFlexibleBand.pm
+t/MyRockBand.pm
+t/MySimpleBand.pm
+
|
redhotpenguin/Class-Factory | 4c147a25ca2933ce01974ee6f5daf3c4670a6565 | add 'use lib' | diff --git a/t/factory.t b/t/factory.t
index e3156d1..b3c8cef 100644
--- a/t/factory.t
+++ b/t/factory.t
@@ -1,62 +1,64 @@
# -*-perl-*-
use strict;
use Test::More tests => 21;
+use lib qw( t );
+
require_ok( 'Class::Factory' );
my $rock_band = 'Slayer';
my $rock_genre = 'ROCK';
my $country_band = 'Plucker';
my $country_genre = 'COUNTRY';
# First do the simple setting
{
require_ok( 'MySimpleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MySimpleBand );
@MyCountryBand::ISA = qw( MySimpleBand );
my $map = MySimpleBand->get_factory_map;
is( ref( $map ), 'HASH', 'Return of get_factory_map()' );
is( scalar keys %{ $map }, 2, 'Keys in map' );
is( $map->{rock}, 'MyRockBand', 'Simple type added 1' );
is( $map->{country}, 'MyCountryBand', 'Simple type added 2' );
my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Simple object returned 1' );
is( $rock->band_name(), $rock_band, 'Simple object super init parameter set 1' );
is( $rock->genre(), $rock_genre, 'Simple object self init parameter set 1' );
my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Simple object returned 2' );
is( $country->band_name(), $country_band, 'Simple object super init parameter set 2' );
is( $country->genre(), $country_genre, 'Simple object self init parameter set 2' );
}
# Next the flexible settting
{
require_ok( 'MyFlexibleBand' );
# Set the ISA of our two bands to the one we're testing now
@MyRockBand::ISA = qw( MyFlexibleBand );
@MyCountryBand::ISA = qw( MyFlexibleBand );
is( MyFlexibleBand->get_factory_type( 'rock' ), 'MyRockBand', 'Flexible type added 1' );
is( MyFlexibleBand->get_factory_type( 'country' ), 'MyCountryBand', 'Flexible type added 2' );
my $rock = MyFlexibleBand->new( 'rock', { band_name => $rock_band } );
is( ref( $rock ), 'MyRockBand', 'Flexible object returned 1' );
is( $rock->band_name(), $rock_band, 'Flexible object super init parameter set 1' );
is( $rock->genre(), $rock_genre, 'Flexible object self init parameter set 1' );
my $country = MyFlexibleBand->new( 'country', { band_name => $country_band } );
is( ref( $country ), 'MyCountryBand', 'Flexible object returned 2' );
is( $country->band_name(), $country_band, 'Flexible object super init parameter set 2' );
is( $country->genre(), $country_genre, 'Flexible object self init parameter set 2' );
}
|
redhotpenguin/Class-Factory | 0b8ea1b6dc9abf172c074e1e165322b369d6bc5b | small doc modifications | diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 6b2fc95..ab7844c 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,336 +1,335 @@
package Class::Factory;
# $Id$
use strict;
$Class::Factory::VERSION = '0.01';
sub get_factory_class {
my ( $item, $factory_type ) = @_;
my $class = ref $item || $item;
my $map = $item->get_factory_map;
my $factory_class = ( ref $map eq 'HASH' )
? $map->{ $factory_type }
: $item->get_factory_type( $factory_type );
unless ( $factory_class ) {
die "Factory type [$factory_type] is not defined in [$class]\n";
}
return $factory_class;
}
sub add_factory_type {
my ( $item, $factory_type, $factory_class ) = @_;
my $class = ref $item || $item;
unless ( $factory_type ) {
die "Cannot add factory type to [$class]: no type defined\n";
}
unless ( $factory_class ) {
die "Cannot add factory type [$factory_type] to [$class]: no class defined\n";
}
my $map = $item->get_factory_map;
my $set_factory_class = ( ref $map eq 'HASH' )
? $map->{ $factory_type }
: $item->get_factory_type( $factory_type );
if ( $set_factory_class ) {
warn "Attempt to add type [$factory_type] to [$class] redundant; ",
"type already exists with class [$set_factory_class]\n";
return;
}
eval "require $factory_class";
if ( $@ ) {
die "Cannot add factory type [$factory_type] to class [$class]: ",
"factory class [$factory_class] cannot be required [$@]\n";
}
if ( ref $map eq 'HASH' ) {
$map->{ $factory_type } = $factory_class;
}
else {
$item->set_factory_type( $factory_type, $factory_class );
}
return $factory_class;
}
########################################
# INTERFACE
# We don't die when these are called because the subclass can define
# either A + B or C
sub get_factory_type { return undef }
sub set_factory_type { return undef }
sub get_factory_map { return undef }
1;
__END__
=head1 NAME
Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub new {
my ( $class, $type, $params ) = @_;
my $factory_class = $class->get_factory_class( $type );
return bless( $params, $factory_class );
}
# SIMPLE: Let the parent know about our types
sub get_factory_map { return \%TYPES }
# FLEXIBLE: Let the parent know about our types
sub get_factory_type {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_type {
my ( $class, $type, $factory_class ) = @_;
$TYPES{ $type } = $factory_class;
}
# Add our default types
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Factory classes are used when you have different implementations for
the same set of tasks but may not know in advance what implementations
you will be using. For instance, take configuration files. There are
four basic operations you would want to do with any configuration
file: read it in, lookup a value, set a value, write it out. There are
also many different types of configuration files, and you may want
users to be able to provide an implementation for their own home-grown
configuration format.
With a factory class this is easy. To create the factory class, just
subclass C<Class::Factory> and create an interface for your
configuration serializer:
package My::ConfigFactory;
use strict;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
sub new {
my ( $class, $type, $filename, @params ) = @_;
my $factory_class = $class->get_factory_class( $type );
my $self = bless( {}, $factory_class );
return $self->initialize( $filename, @params );
}
sub read { die "Define read() in implementation" }
sub write { die "Define write() in implementation" }
sub get { die "Define get() in implementation" }
sub set { die "Define set() in implementation" }
1;
And then users can add their own subclasses:
package My::CustomConfig;
use strict;
use base qw( My::ConfigFactory );
sub initialize {
my ( $self, $filename, $params ) = @_;
if ( $params->{base_url} ) {
$self->read_from_web( join( '/', $params->{base_url}, $filename ) );
}
else {
$self->read( $filename );
}
return $self;
}
sub read { ... implementation to read a file ... }
sub write { ... implementation to write a file ... }
sub get { ... implementation to get a value ... }
sub set { ... implementation to set a value ... }
sub read_from_web { ... implementation to read via http ... }
1;
(Normally you probably would not make your factory the same as your
interface, but this is an abbreviated example.)
So now users can use the custom configuration with something like:
#!/usr/bin/perl
use strict;
use My::ConfigFactory;
My::ConfigFactory->add_factory_type( 'custom' => 'My::CustomConfig' );
my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
This might not seem like a very big win, and for small standalone
applications it is not. But when you develop large applications the
C<add_factory_type()> step will almost certainly be done at
-application initialization time as a result of processing metadata
-about the instantiation of the application. And then users of the
-application can access the different types as if they are part of the
-system.
+application initialization time, hidden away from the eyes of the
+application developer. That developer will only know that she can
+access the different object types as if they are part of the system.
As you see in the example above, implementation for subclasses is very
simple. The base class defines two methods for subclasses to use:
C<get_factory_class()> and C<add_factory_type()>. Subclasses must
define either C<get_factory_map()> or both C<get_factory_type()> and
C<set_factory_type()>.
=head1 METHODS
B<get_factory_class( $object_type )>
Usually called from a constructor when you want to lookup a class by a
type and create a new object of C<$object_type>.
Returns: name of class. If a class matching C<$object_type> is not
found, then a C<die()> is thrown.
B<add_factory_type( $object_type, $object_class )>
Tells the factory to dynamically add a new type to its stable and
brings in the class implementing that type using C<require()>. After
running this the factory class will be able to create new objects of
type C<$object_type>.
Returns: name of class added if successful. If the proper parameters
are not given or if we cannot find C<$object_class> in @INC, then a
C<die()> is thrown.
=head1 SUBCLASSING
You can do this either the simple way or the flexible way. For most
cases, the simple way will suffice:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
If you elect to use the flexible way, you need to implement two
methods:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_class {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_class {
my ( $class, $type, $object_class ) = @_;
return $TYPES{ $type } = $object_class;
}
How these methods work is entirely up to you -- maybe
C<get_factory_class()> does a lookup in some external resource before
returning the class. Whatever floats your boat.
=head1 USAGE
=head2 Common Pattern
This is a very common pattern. Subclasses create an C<initialize()>
method that gets called when the object is created:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
sub new {
my ( $class, $type, @params ) = @_;
my $object_class = $class->get_factory_class( $type );
my $self = bless( {}, $object_class );
return $self->initialize( @params );
}
1;
And here is what a subclass might look like:
package My::Subclass;
use base qw( Class::Accessor );
my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we've taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub initialize {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
$self->filename( filename );
$self->read_file_contents;
foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
John Vlissides. Addison Wesley Longman, 1995. Specifically, the
'Factory Method' pattern at pp. 107-116.
=head1 AUTHOR
Chris Winters <[email protected]>
=cut
|
redhotpenguin/Class-Factory | a9895f374eb610bc9e446f18c293fef38daf30eb | add lots of docs | diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 4c5f820..6b2fc95 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,233 +1,336 @@
package Class::Factory;
# $Id$
use strict;
$Class::Factory::VERSION = '0.01';
sub get_factory_class {
my ( $item, $factory_type ) = @_;
my $class = ref $item || $item;
my $map = $item->get_factory_map;
my $factory_class = ( ref $map eq 'HASH' )
? $map->{ $factory_type }
: $item->get_factory_type( $factory_type );
unless ( $factory_class ) {
die "Factory type [$factory_type] is not defined in [$class]\n";
}
return $factory_class;
}
sub add_factory_type {
my ( $item, $factory_type, $factory_class ) = @_;
my $class = ref $item || $item;
unless ( $factory_type ) {
die "Cannot add factory type to [$class]: no type defined\n";
}
unless ( $factory_class ) {
die "Cannot add factory type [$factory_type] to [$class]: no class defined\n";
}
my $map = $item->get_factory_map;
my $set_factory_class = ( ref $map eq 'HASH' )
? $map->{ $factory_type }
: $item->get_factory_type( $factory_type );
if ( $set_factory_class ) {
warn "Attempt to add type [$factory_type] to [$class] redundant; ",
"type already exists with class [$set_factory_class]\n";
return;
}
eval "require $factory_class";
if ( $@ ) {
die "Cannot add factory type [$factory_type] to class [$class]: ",
"factory class [$factory_class] cannot be required [$@]\n";
}
if ( ref $map eq 'HASH' ) {
$map->{ $factory_type } = $factory_class;
}
else {
$item->set_factory_type( $factory_type, $factory_class );
}
return $factory_class;
}
########################################
# INTERFACE
# We don't die when these are called because the subclass can define
# either A + B or C
sub get_factory_type { return undef }
sub set_factory_type { return undef }
sub get_factory_map { return undef }
1;
__END__
-
=head1 NAME
-Class::Factory - Base class for factory classes
+Class::Factory - Base class for dynamic factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub new {
my ( $class, $type, $params ) = @_;
my $factory_class = $class->get_factory_class( $type );
return bless( $params, $factory_class );
}
# SIMPLE: Let the parent know about our types
sub get_factory_map { return \%TYPES }
# FLEXIBLE: Let the parent know about our types
sub get_factory_type {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_type {
my ( $class, $type, $factory_class ) = @_;
$TYPES{ $type } = $factory_class;
}
# Add our default types
- My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
+ My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
-Implementation for subclasses is very simple. The base class defines
-two methods for subclasses to use: C<get_factory_class()> and
-C<add_factory_type()>. Subclasses must define either
-C<get_factory_map()> or both C<get_factory_type()> and
+Factory classes are used when you have different implementations for
+the same set of tasks but may not know in advance what implementations
+you will be using. For instance, take configuration files. There are
+four basic operations you would want to do with any configuration
+file: read it in, lookup a value, set a value, write it out. There are
+also many different types of configuration files, and you may want
+users to be able to provide an implementation for their own home-grown
+configuration format.
+
+With a factory class this is easy. To create the factory class, just
+subclass C<Class::Factory> and create an interface for your
+configuration serializer:
+
+ package My::ConfigFactory;
+
+ use strict;
+ use base qw( Class::Factory );
+
+ my %TYPES = ();
+ sub get_factory_map { return \%TYPES }
+
+ sub new {
+ my ( $class, $type, $filename, @params ) = @_;
+ my $factory_class = $class->get_factory_class( $type );
+ my $self = bless( {}, $factory_class );
+ return $self->initialize( $filename, @params );
+ }
+
+ sub read { die "Define read() in implementation" }
+ sub write { die "Define write() in implementation" }
+ sub get { die "Define get() in implementation" }
+ sub set { die "Define set() in implementation" }
+
+ 1;
+
+And then users can add their own subclasses:
+
+ package My::CustomConfig;
+
+ use strict;
+ use base qw( My::ConfigFactory );
+
+ sub initialize {
+ my ( $self, $filename, $params ) = @_;
+ if ( $params->{base_url} ) {
+ $self->read_from_web( join( '/', $params->{base_url}, $filename ) );
+ }
+ else {
+ $self->read( $filename );
+ }
+ return $self;
+ }
+
+ sub read { ... implementation to read a file ... }
+ sub write { ... implementation to write a file ... }
+ sub get { ... implementation to get a value ... }
+ sub set { ... implementation to set a value ... }
+
+ sub read_from_web { ... implementation to read via http ... }
+
+ 1;
+
+(Normally you probably would not make your factory the same as your
+interface, but this is an abbreviated example.)
+
+So now users can use the custom configuration with something like:
+
+ #!/usr/bin/perl
+
+ use strict;
+ use My::ConfigFactory;
+
+ My::ConfigFactory->add_factory_type( 'custom' => 'My::CustomConfig' );
+
+ my $config = My::ConfigFactory->new( 'custom', 'myconf.dat' );
+
+This might not seem like a very big win, and for small standalone
+applications it is not. But when you develop large applications the
+C<add_factory_type()> step will almost certainly be done at
+application initialization time as a result of processing metadata
+about the instantiation of the application. And then users of the
+application can access the different types as if they are part of the
+system.
+
+As you see in the example above, implementation for subclasses is very
+simple. The base class defines two methods for subclasses to use:
+C<get_factory_class()> and C<add_factory_type()>. Subclasses must
+define either C<get_factory_map()> or both C<get_factory_type()> and
C<set_factory_type()>.
=head1 METHODS
-B<get_factory_class( $factory_type )>
+B<get_factory_class( $object_type )>
+
+Usually called from a constructor when you want to lookup a class by a
+type and create a new object of C<$object_type>.
-B<add_factory_type( $factory_type, $factory_class )>
+Returns: name of class. If a class matching C<$object_type> is not
+found, then a C<die()> is thrown.
+
+B<add_factory_type( $object_type, $object_class )>
+
+Tells the factory to dynamically add a new type to its stable and
+brings in the class implementing that type using C<require()>. After
+running this the factory class will be able to create new objects of
+type C<$object_type>.
+
+Returns: name of class added if successful. If the proper parameters
+are not given or if we cannot find C<$object_class> in @INC, then a
+C<die()> is thrown.
=head1 SUBCLASSING
You can do this either the simple way or the flexible way. For most
cases, the simple way will suffice:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
If you elect to use the flexible way, you need to implement two
methods:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_class {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_class {
- my ( $class, $type, $factory_class ) = @_;
- return $TYPES{ $type } = $factory_class;
+ my ( $class, $type, $object_class ) = @_;
+ return $TYPES{ $type } = $object_class;
}
How these methods work is entirely up to you -- maybe
C<get_factory_class()> does a lookup in some external resource before
returning the class. Whatever floats your boat.
=head1 USAGE
=head2 Common Pattern
This is a very common pattern. Subclasses create an C<initialize()>
method that gets called when the object is created:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
sub new {
my ( $class, $type, @params ) = @_;
- my $factory_class = $class->get_factory_class( $type );
- my $self = bless( {}, $factory_class );
+ my $object_class = $class->get_factory_class( $type );
+ my $self = bless( {}, $object_class );
return $self->initialize( @params );
}
1;
And here is what a subclass might look like:
package My::Subclass;
use base qw( Class::Accessor );
- my @FIELDS = qw( filename status );
+ my @CONFIG_FIELDS = qw( status created_on created_by updated_on updated_by );
+ my @FIELDS = ( 'filename', @CONFIG_FIELDS );
My::Subclass->mk_accessors( @FIELDS );
# Note: we've taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub initialize {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
- foreach my $field ( @FIELDS ) {
+ $self->filename( filename );
+ $self->read_file_contents;
+ foreach my $field ( @CONFIG_FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
-L<perl>.
+"Design Patterns", by Erich Gamma, Richard Helm, Ralph Johnson and
+John Vlissides. Addison Wesley Longman, 1995. Specifically, the
+'Factory Method' pattern at pp. 107-116.
=head1 AUTHOR
Chris Winters <[email protected]>
=cut
|
redhotpenguin/Class-Factory | 0070f8b92919186cf3ec8e97a68c9b7551e35c58 | remove extra declaration | diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 39023d3..4c5f820 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,233 +1,233 @@
package Class::Factory;
# $Id$
use strict;
$Class::Factory::VERSION = '0.01';
sub get_factory_class {
my ( $item, $factory_type ) = @_;
my $class = ref $item || $item;
my $map = $item->get_factory_map;
my $factory_class = ( ref $map eq 'HASH' )
? $map->{ $factory_type }
: $item->get_factory_type( $factory_type );
unless ( $factory_class ) {
die "Factory type [$factory_type] is not defined in [$class]\n";
}
return $factory_class;
}
sub add_factory_type {
my ( $item, $factory_type, $factory_class ) = @_;
my $class = ref $item || $item;
unless ( $factory_type ) {
die "Cannot add factory type to [$class]: no type defined\n";
}
unless ( $factory_class ) {
die "Cannot add factory type [$factory_type] to [$class]: no class defined\n";
}
my $map = $item->get_factory_map;
my $set_factory_class = ( ref $map eq 'HASH' )
? $map->{ $factory_type }
: $item->get_factory_type( $factory_type );
if ( $set_factory_class ) {
warn "Attempt to add type [$factory_type] to [$class] redundant; ",
"type already exists with class [$set_factory_class]\n";
return;
}
eval "require $factory_class";
if ( $@ ) {
die "Cannot add factory type [$factory_type] to class [$class]: ",
"factory class [$factory_class] cannot be required [$@]\n";
}
- my $map = $item->get_factory_map;
+
if ( ref $map eq 'HASH' ) {
$map->{ $factory_type } = $factory_class;
}
else {
$item->set_factory_type( $factory_type, $factory_class );
}
return $factory_class;
}
########################################
# INTERFACE
# We don't die when these are called because the subclass can define
# either A + B or C
sub get_factory_type { return undef }
sub set_factory_type { return undef }
sub get_factory_map { return undef }
1;
__END__
=head1 NAME
Class::Factory - Base class for factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub new {
my ( $class, $type, $params ) = @_;
my $factory_class = $class->get_factory_class( $type );
return bless( $params, $factory_class );
}
# SIMPLE: Let the parent know about our types
sub get_factory_map { return \%TYPES }
# FLEXIBLE: Let the parent know about our types
sub get_factory_type {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_type {
my ( $class, $type, $factory_class ) = @_;
$TYPES{ $type } = $factory_class;
}
# Add our default types
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
types of objects on the fly, providing a consistent interface to
common groups of objects.
Implementation for subclasses is very simple. The base class defines
two methods for subclasses to use: C<get_factory_class()> and
C<add_factory_type()>. Subclasses must define either
C<get_factory_map()> or both C<get_factory_type()> and
C<set_factory_type()>.
=head1 METHODS
B<get_factory_class( $factory_type )>
B<add_factory_type( $factory_type, $factory_class )>
=head1 SUBCLASSING
You can do this either the simple way or the flexible way. For most
cases, the simple way will suffice:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
If you elect to use the flexible way, you need to implement two
methods:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_class {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_class {
my ( $class, $type, $factory_class ) = @_;
return $TYPES{ $type } = $factory_class;
}
How these methods work is entirely up to you -- maybe
C<get_factory_class()> does a lookup in some external resource before
returning the class. Whatever floats your boat.
=head1 USAGE
=head2 Common Pattern
This is a very common pattern. Subclasses create an C<initialize()>
method that gets called when the object is created:
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub get_factory_map { return \%TYPES }
sub new {
my ( $class, $type, @params ) = @_;
my $factory_class = $class->get_factory_class( $type );
my $self = bless( {}, $factory_class );
return $self->initialize( @params );
}
1;
And here is what a subclass might look like:
package My::Subclass;
use base qw( Class::Accessor );
my @FIELDS = qw( filename status );
My::Subclass->mk_accessors( @FIELDS );
# Note: we've taken the flattened C<@params> passed in and assigned
# the first element as C<$filename> and the other element as a
# hashref C<$params>
sub initialize {
my ( $self, $filename, $params ) = @_;
unless ( -f $filename ) {
die "Filename [$filename] does not exist. Object cannot be created";
}
foreach my $field ( @FIELDS ) {
$self->{ $field } = $params->{ $field } if ( $params->{ $field } );
}
return $self;
}
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
L<perl>.
=head1 AUTHOR
Chris Winters <[email protected]>
=cut
|
redhotpenguin/Class-Factory | a76f6c4509985926b42ec0682a80b355c2946d27 | add Test::More as prereq | diff --git a/Makefile.PL b/Makefile.PL
index ea12f33..a9c1d1d 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,13 +1,14 @@
use ExtUtils::MakeMaker;
my %opts = (
'NAME' => 'Class::Factory',
'VERSION_FROM' => 'lib/Class/Factory.pm',
+ 'PREREQ_PM' => { 'Test::More' => 0.40, }
);
-if ($ExtUtils::MakeMaker::VERSION >= 5.43) {
+if ( $ExtUtils::MakeMaker::VERSION >= 5.43 ) {
$opts{AUTHOR} = 'Chris Winters <[email protected]';
$opts{ABSTRACT} = 'Useful base class for factory classes',
}
WriteMakefile( %opts );
|
redhotpenguin/Class-Factory | 731e77c449fcff9ec75ae69cfb6a310e9e63a0a6 | fix dumb naming issue | diff --git a/lib/Class/Factory.pm b/lib/Class/Factory.pm
index 93e5b90..39023d3 100644
--- a/lib/Class/Factory.pm
+++ b/lib/Class/Factory.pm
@@ -1,147 +1,233 @@
package Class::Factory;
# $Id$
use strict;
$Class::Factory::VERSION = '0.01';
sub get_factory_class {
my ( $item, $factory_type ) = @_;
my $class = ref $item || $item;
my $map = $item->get_factory_map;
my $factory_class = ( ref $map eq 'HASH' )
? $map->{ $factory_type }
: $item->get_factory_type( $factory_type );
unless ( $factory_class ) {
die "Factory type [$factory_type] is not defined in [$class]\n";
}
return $factory_class;
}
sub add_factory_type {
my ( $item, $factory_type, $factory_class ) = @_;
my $class = ref $item || $item;
unless ( $factory_type ) {
die "Cannot add factory type to [$class]: no type defined\n";
}
unless ( $factory_class ) {
die "Cannot add factory type [$factory_type] to [$class]: no class defined\n";
}
- my $factory_class = $item->get_factory_type( $factory_type );
- if ( $factory_class ) {
+ my $map = $item->get_factory_map;
+ my $set_factory_class = ( ref $map eq 'HASH' )
+ ? $map->{ $factory_type }
+ : $item->get_factory_type( $factory_type );
+ if ( $set_factory_class ) {
warn "Attempt to add type [$factory_type] to [$class] redundant; ",
- "type already exists with class [$class]\n";
+ "type already exists with class [$set_factory_class]\n";
return;
}
eval "require $factory_class";
if ( $@ ) {
die "Cannot add factory type [$factory_type] to class [$class]: ",
"factory class [$factory_class] cannot be required [$@]\n";
}
my $map = $item->get_factory_map;
if ( ref $map eq 'HASH' ) {
$map->{ $factory_type } = $factory_class;
}
else {
$item->set_factory_type( $factory_type, $factory_class );
}
return $factory_class;
}
########################################
# INTERFACE
# We don't die when these are called because the subclass can define
# either A + B or C
sub get_factory_type { return undef }
sub set_factory_type { return undef }
sub get_factory_map { return undef }
1;
__END__
=head1 NAME
Class::Factory - Base class for factory classes
=head1 SYNOPSIS
package My::Factory;
use base qw( Class::Factory );
my %TYPES = ();
sub new {
my ( $class, $type, $params ) = @_;
my $factory_class = $class->get_factory_class( $type );
return bless( $params, $factory_class );
}
# SIMPLE: Let the parent know about our types
sub get_factory_map { return \%TYPES }
# FLEXIBLE: Let the parent know about our types
sub get_factory_type {
my ( $class, $type ) = @_;
return $TYPES{ $type };
}
sub set_factory_type {
my ( $class, $type, $factory_class ) = @_;
$TYPES{ $type } = $factory_class;
}
# Add our default types
My::Factory->add_factory_type( perl => 'My::Factory::Perl' );
My::Factory->add_factory_type( blech => 'My::Factory::Blech' );
1;
# Adding a new factory type in code
My::Factory->add_factory_type( custom => 'Other::Custom::Class' );
my $custom_object = My::Factory->new( 'custom', { this => 'that' } );
=head1 DESCRIPTION
This is a simple module that factory classes can use to generate new
-types of objects on the fly. The base class defines two methods for
-subclasses to use: C<get_factory_class()> and
+types of objects on the fly, providing a consistent interface to
+common groups of objects.
+
+Implementation for subclasses is very simple. The base class defines
+two methods for subclasses to use: C<get_factory_class()> and
C<add_factory_type()>. Subclasses must define either
C<get_factory_map()> or both C<get_factory_type()> and
C<set_factory_type()>.
=head1 METHODS
B<get_factory_class( $factory_type )>
B<add_factory_type( $factory_type, $factory_class )>
+=head1 SUBCLASSING
+
+You can do this either the simple way or the flexible way. For most
+cases, the simple way will suffice:
+
+ package My::Factory;
+
+ use base qw( Class::Factory );
+
+ my %TYPES = ();
+ sub get_factory_map { return \%TYPES }
+
+If you elect to use the flexible way, you need to implement two
+methods:
+
+ package My::Factory;
+
+ use base qw( Class::Factory );
+
+ my %TYPES = ();
+ sub get_factory_class {
+ my ( $class, $type ) = @_;
+ return $TYPES{ $type };
+ }
+
+ sub set_factory_class {
+ my ( $class, $type, $factory_class ) = @_;
+ return $TYPES{ $type } = $factory_class;
+ }
+
+How these methods work is entirely up to you -- maybe
+C<get_factory_class()> does a lookup in some external resource before
+returning the class. Whatever floats your boat.
+
+=head1 USAGE
+
+=head2 Common Pattern
+
+This is a very common pattern. Subclasses create an C<initialize()>
+method that gets called when the object is created:
+
+ package My::Factory;
+
+ use base qw( Class::Factory );
+
+ my %TYPES = ();
+ sub get_factory_map { return \%TYPES }
+
+ sub new {
+ my ( $class, $type, @params ) = @_;
+ my $factory_class = $class->get_factory_class( $type );
+ my $self = bless( {}, $factory_class );
+ return $self->initialize( @params );
+ }
+
+ 1;
+
+And here is what a subclass might look like:
+
+ package My::Subclass;
+
+ use base qw( Class::Accessor );
+ my @FIELDS = qw( filename status );
+ My::Subclass->mk_accessors( @FIELDS );
+
+ # Note: we've taken the flattened C<@params> passed in and assigned
+ # the first element as C<$filename> and the other element as a
+ # hashref C<$params>
+
+ sub initialize {
+ my ( $self, $filename, $params ) = @_;
+ unless ( -f $filename ) {
+ die "Filename [$filename] does not exist. Object cannot be created";
+ }
+ foreach my $field ( @FIELDS ) {
+ $self->{ $field } = $params->{ $field } if ( $params->{ $field } );
+ }
+ return $self;
+ }
+
=head1 COPYRIGHT
Copyright (c) 2002 Chris Winters. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
L<perl>.
=head1 AUTHOR
Chris Winters <[email protected]>
=cut
|
redhotpenguin/Class-Factory | 1b454d857ade4ce8b06bed1fc4d68b529319785a | add test script plus supporting classes | diff --git a/t/MyCountryBand.pm b/t/MyCountryBand.pm
new file mode 100644
index 0000000..0652541
--- /dev/null
+++ b/t/MyCountryBand.pm
@@ -0,0 +1,14 @@
+package MyCountryBand;
+
+use strict;
+
+# Note: @ISA is modified during the test
+
+sub initialize {
+ my ( $self, $params ) = @_;
+ $self->SUPER::initialize( $params );
+ $self->genre( 'COUNTRY' );
+ return $self;
+}
+
+1;
diff --git a/t/MyFlexibleBand.pm b/t/MyFlexibleBand.pm
new file mode 100644
index 0000000..0a6c5ed
--- /dev/null
+++ b/t/MyFlexibleBand.pm
@@ -0,0 +1,43 @@
+package MyFlexibleBand;
+
+# $Id$
+
+use strict;
+use base qw( Class::Factory );
+
+my %TYPES = ();
+sub get_factory_type { return $TYPES{ $_[1] } }
+sub set_factory_type { return $TYPES{ $_[1] } = $_[2] }
+
+sub new {
+ my ( $class, $type, $params ) = @_;
+ my $factory_class = $class->get_factory_class( $type );
+ my $self = bless( {}, $factory_class );
+ return $self->initialize( $params );
+}
+
+
+sub initialize {
+ my ( $self, $params ) = @_;
+ $self->band_name( $params->{band_name} );
+ return $self;
+}
+
+
+sub band_name {
+ my ( $self, $name ) = @_;
+ $self->{band_name} = $name if ( $name );
+ return $self->{band_name};
+}
+
+sub genre {
+ my ( $self, $genre ) = @_;
+ $self->{genre} = $genre if ( $genre );
+ return $self->{genre};
+}
+
+MyFlexibleBand->add_factory_type( rock => 'MyRockBand' );
+MyFlexibleBand->add_factory_type( country => 'MyCountryBand' );
+
+1;
+
diff --git a/t/MyRockBand.pm b/t/MyRockBand.pm
new file mode 100644
index 0000000..274627c
--- /dev/null
+++ b/t/MyRockBand.pm
@@ -0,0 +1,14 @@
+package MyRockBand;
+
+use strict;
+
+# Note: @ISA is modified during the test
+
+sub initialize {
+ my ( $self, $params ) = @_;
+ $self->SUPER::initialize( $params );
+ $self->genre( 'ROCK' );
+ return $self;
+}
+
+1;
diff --git a/t/MySimpleBand.pm b/t/MySimpleBand.pm
new file mode 100644
index 0000000..1ea95d8
--- /dev/null
+++ b/t/MySimpleBand.pm
@@ -0,0 +1,45 @@
+package MySimpleBand;
+
+# $Id$
+
+use strict;
+use base qw( Class::Factory );
+
+#use Class::Factory;
+#@MySimpleBand::ISA = qw( Class::Factory );
+
+my %TYPES = ();
+sub get_factory_map { return \%TYPES }
+
+sub new {
+ my ( $class, $type, $params ) = @_;
+ my $factory_class = $class->get_factory_class( $type );
+ my $self = bless( {}, $factory_class );
+ return $self->initialize( $params );
+}
+
+
+sub initialize {
+ my ( $self, $params ) = @_;
+ $self->band_name( $params->{band_name} );
+ return $self;
+}
+
+
+sub band_name {
+ my ( $self, $name ) = @_;
+ $self->{band_name} = $name if ( $name );
+ return $self->{band_name};
+}
+
+sub genre {
+ my ( $self, $genre ) = @_;
+ $self->{genre} = $genre if ( $genre );
+ return $self->{genre};
+}
+
+MySimpleBand->add_factory_type( rock => 'MyRockBand' );
+MySimpleBand->add_factory_type( country => 'MyCountryBand' );
+
+1;
+
diff --git a/t/factory.t b/t/factory.t
new file mode 100644
index 0000000..e3156d1
--- /dev/null
+++ b/t/factory.t
@@ -0,0 +1,62 @@
+# -*-perl-*-
+
+use strict;
+use Test::More tests => 21;
+
+require_ok( 'Class::Factory' );
+
+my $rock_band = 'Slayer';
+my $rock_genre = 'ROCK';
+my $country_band = 'Plucker';
+my $country_genre = 'COUNTRY';
+
+# First do the simple setting
+
+{
+ require_ok( 'MySimpleBand' );
+
+ # Set the ISA of our two bands to the one we're testing now
+
+ @MyRockBand::ISA = qw( MySimpleBand );
+ @MyCountryBand::ISA = qw( MySimpleBand );
+
+ my $map = MySimpleBand->get_factory_map;
+ is( ref( $map ), 'HASH', 'Return of get_factory_map()' );
+ is( scalar keys %{ $map }, 2, 'Keys in map' );
+ is( $map->{rock}, 'MyRockBand', 'Simple type added 1' );
+ is( $map->{country}, 'MyCountryBand', 'Simple type added 2' );
+
+ my $rock = MySimpleBand->new( 'rock', { band_name => $rock_band } );
+ is( ref( $rock ), 'MyRockBand', 'Simple object returned 1' );
+ is( $rock->band_name(), $rock_band, 'Simple object super init parameter set 1' );
+ is( $rock->genre(), $rock_genre, 'Simple object self init parameter set 1' );
+
+ my $country = MySimpleBand->new( 'country', { band_name => $country_band } );
+ is( ref( $country ), 'MyCountryBand', 'Simple object returned 2' );
+ is( $country->band_name(), $country_band, 'Simple object super init parameter set 2' );
+ is( $country->genre(), $country_genre, 'Simple object self init parameter set 2' );
+}
+
+# Next the flexible settting
+
+{
+ require_ok( 'MyFlexibleBand' );
+
+ # Set the ISA of our two bands to the one we're testing now
+
+ @MyRockBand::ISA = qw( MyFlexibleBand );
+ @MyCountryBand::ISA = qw( MyFlexibleBand );
+
+ is( MyFlexibleBand->get_factory_type( 'rock' ), 'MyRockBand', 'Flexible type added 1' );
+ is( MyFlexibleBand->get_factory_type( 'country' ), 'MyCountryBand', 'Flexible type added 2' );
+
+ my $rock = MyFlexibleBand->new( 'rock', { band_name => $rock_band } );
+ is( ref( $rock ), 'MyRockBand', 'Flexible object returned 1' );
+ is( $rock->band_name(), $rock_band, 'Flexible object super init parameter set 1' );
+ is( $rock->genre(), $rock_genre, 'Flexible object self init parameter set 1' );
+
+ my $country = MyFlexibleBand->new( 'country', { band_name => $country_band } );
+ is( ref( $country ), 'MyCountryBand', 'Flexible object returned 2' );
+ is( $country->band_name(), $country_band, 'Flexible object super init parameter set 2' );
+ is( $country->genre(), $country_genre, 'Flexible object self init parameter set 2' );
+}
|
redhotpenguin/Class-Factory | 85a3195833833adb8e4fc8473f19bbbb67fa8f8a | modified to use file in lib/Class | diff --git a/Makefile.PL b/Makefile.PL
index 08e8a63..ea12f33 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,12 +1,13 @@
use ExtUtils::MakeMaker;
-# See lib/ExtUtils/MakeMaker.pm for details of how to influence
-# the contents of the Makefile that is written.
-WriteMakefile(
- 'NAME' => 'Class::Factory',
- 'VERSION_FROM' => 'Factory.pm', # finds $VERSION
- 'PREREQ_PM' => {},
- ($] >= 5.005 ?
- (ABSTRACT_FROM => 'Factory.pm',
- AUTHOR => 'Chris Winters <[email protected]') : ()),
+my %opts = (
+ 'NAME' => 'Class::Factory',
+ 'VERSION_FROM' => 'lib/Class/Factory.pm',
);
+
+if ($ExtUtils::MakeMaker::VERSION >= 5.43) {
+ $opts{AUTHOR} = 'Chris Winters <[email protected]';
+ $opts{ABSTRACT} = 'Useful base class for factory classes',
+}
+
+WriteMakefile( %opts );
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.