V2.0 update

## Features 

### Open
* Now returns the activeDocument after opening the file.

### JSLayer()
* Removed semicolon from output.

### Document
* Added FullName() which returns path to the .psd file.
* Changed Filename() to DumpFile(), as Filename was misleading.
* Dump function now saves the file as well,
to help reduce the frequency of de-syncs.
* Dump function now saves json files alongside the .psds
instead of in a separate data folder- encountered issues when using
the package as a module in go 1.11beta2.
* Added Save()

## Testing
* Added TestDocument_Save
* Added TestDocument_Dump

## Misc.
* Renamed pkgpath to pkgPath, to better fit go's standards.

## Fixes
* DoAction now runs correctly.
This commit is contained in:
Spencer
2018-07-24 20:23:48 -04:00
committed by Unknown
parent 2f335aec00
commit bf5e4f9b99
13 changed files with 171 additions and 54 deletions

View File

@@ -1,5 +1,5 @@
![logo](logo.png) ![logo](logo.png)
# ps
[![GoDoc](https://godoc.org/github.com/sbrow/ps?status.svg)](https://godoc.org/github.com/sbrow/ps) [![Build Status](https://travis-ci.org/sbrow/ps.svg?branch=master)](https://travis-ci.org/sbrow/ps) [![Coverage Status](https://coveralls.io/repos/github/sbrow/ps/badge.svg?branch=master)](https://coveralls.io/github/sbrow/ps?branch=master) [![Go Report Card](https://goreportcard.com/badge/github.com/sbrow/ps)](https://goreportcard.com/report/github.com/sbrow/ps) [![GoDoc](https://godoc.org/github.com/sbrow/ps?status.svg)](https://godoc.org/github.com/sbrow/ps) [![Build Status](https://travis-ci.org/sbrow/ps.svg?branch=master)](https://travis-ci.org/sbrow/ps) [![Coverage Status](https://coveralls.io/repos/github/sbrow/ps/badge.svg?branch=master)](https://coveralls.io/github/sbrow/ps?branch=master) [![Go Report Card](https://goreportcard.com/badge/github.com/sbrow/ps)](https://goreportcard.com/report/github.com/sbrow/ps)
`import "github.com/sbrow/ps"` `import "github.com/sbrow/ps"`
@@ -39,12 +39,10 @@ $ go get -u github.com/sbrow/ps
`sbrow:` (2) Make TextLayer a subclass of ArtLayer. `sbrow:` (2) Make TextLayer a subclass of ArtLayer.
`sbrow:` Reduce cylcomatic complexity of ActiveDocument(). `sbrow:` Reduce cyclomatic complexity of ActiveDocument().
`sbrow:` refactor Close to Document.Close `sbrow:` refactor Close to Document.Close
`sbrow:` get rid of the semicolon at the end of JSLayer.
## <a name="pkg-doc">Documentation</a> ## <a name="pkg-doc">Documentation</a>
For full Documentation please visit https://godoc.org/github.com/sbrow/ps For full Documentation please visit https://godoc.org/github.com/sbrow/ps
- - - - - -

View File

@@ -4,7 +4,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
"strings"
"github.com/sbrow/ps/runner" "github.com/sbrow/ps/runner"
) )
@@ -211,8 +210,7 @@ func (a *ArtLayer) SetVisible(b bool) error {
case false: case false:
log.Printf("Hiding %s", a.name) log.Printf("Hiding %s", a.name)
} }
js := fmt.Sprintf("%s.visible=%v;", js := fmt.Sprintf("%s.visible=%v;", JSLayer(a.Path()), b)
strings.TrimRight(JSLayer(a.Path()), ";"), b)
if byt, err := DoJS("compilejs.jsx", js); err != nil { if byt, err := DoJS("compilejs.jsx", js); err != nil {
log.Println(string(byt)) log.Println(string(byt))
return err return err

View File

@@ -2,17 +2,19 @@ package ps
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io/ioutil" "io/ioutil"
"log" "log"
"os" "os"
"os/user"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
) )
// Document represents a Photoshop document (PSD file). // Document represents a Photoshop document (PSD file).
type Document struct { type Document struct {
name string name string
fullName string
height int height int
width int width int
artLayers []*ArtLayer artLayers []*ArtLayer
@@ -23,6 +25,7 @@ type Document struct {
// allows Documents to be saved to and loaded from JSON. // allows Documents to be saved to and loaded from JSON.
type DocumentJSON struct { type DocumentJSON struct {
Name string Name string
FullName string
Height int Height int
Width int Width int
ArtLayers []*ArtLayer ArtLayers []*ArtLayer
@@ -31,7 +34,7 @@ type DocumentJSON struct {
// MarshalJSON returns the Document in JSON format. // MarshalJSON returns the Document in JSON format.
func (d *Document) MarshalJSON() ([]byte, error) { func (d *Document) MarshalJSON() ([]byte, error) {
return json.Marshal(&DocumentJSON{Name: d.name, Height: d.height, return json.Marshal(&DocumentJSON{Name: d.name, FullName: d.fullName, Height: d.height,
Width: d.width, ArtLayers: d.artLayers, LayerSets: d.layerSets}) Width: d.width, ArtLayers: d.artLayers, LayerSets: d.layerSets})
} }
@@ -42,6 +45,7 @@ func (d *Document) UnmarshalJSON(b []byte) error {
return err return err
} }
d.name = tmp.Name d.name = tmp.Name
d.fullName = tmp.FullName
d.height = tmp.Height d.height = tmp.Height
d.width = tmp.Width d.width = tmp.Width
d.artLayers = tmp.ArtLayers d.artLayers = tmp.ArtLayers
@@ -61,6 +65,11 @@ func (d *Document) Name() string {
return d.name return d.name
} }
// FullName returns the absolute path to the current document file.
func (d *Document) FullName() string {
return d.fullName
}
// Parent returns the Group that contains d. // Parent returns the Group that contains d.
func (d *Document) Parent() Group { func (d *Document) Parent() Group {
return nil return nil
@@ -127,7 +136,7 @@ func ActiveDocument() (*Document, error) {
} }
d.name = strings.TrimRight(string(byt), "\r\n") d.name = strings.TrimRight(string(byt), "\r\n")
if Mode != Safe { if Mode != Safe {
err = d.Restore(d.Filename()) err = d.Restore(d.DumpFile())
switch { switch {
case os.IsNotExist(err): case os.IsNotExist(err):
log.Println("Previous version not found.") log.Println("Previous version not found.")
@@ -165,7 +174,7 @@ func ActiveDocument() (*Document, error) {
// Restore loads document data from a JSON file. // Restore loads document data from a JSON file.
func (d *Document) Restore(path string) error { func (d *Document) Restore(path string) error {
if path == "" { if path == "" {
path = d.Filename() path = d.DumpFile()
} }
byt, err := ioutil.ReadFile(path) byt, err := ioutil.ReadFile(path)
if err == nil { if err == nil {
@@ -185,26 +194,23 @@ func (d *Document) Path() string {
return "" return ""
} }
// Filename returns the path to the json file for this document. // DumpFile returns the path to the json file where
func (d *Document) Filename() string { // this document's data gets dumped. See Document.Dump
_, dir, _, ok := runtime.Caller(0) func (d *Document) DumpFile() string {
if !ok { usr, err := user.Current()
log.Panic("No caller information")
}
err := os.Mkdir(filepath.Join(filepath.Dir(dir), "data"), 0700)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
name := strings.TrimRight(d.name, "\r\n") path := filepath.Join(strings.Replace(d.fullName, "~", usr.HomeDir, 1))
name = strings.TrimSuffix(name, ".psd") return strings.Replace(path, ".psd", ".json", 1)
return filepath.Join(filepath.Dir(dir), "data", name+".json")
} }
// Dump saves the document to disk in JSON format. // Dump saves the document to disk in JSON format.
func (d *Document) Dump() { func (d *Document) Dump() {
log.Println("Dumping to disk") log.Println("Dumping to disk")
log.Println(d.Filename()) log.Println(d.DumpFile())
f, err := os.Create(d.Filename()) defer d.Save()
f, err := os.Create(d.DumpFile())
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -238,3 +244,12 @@ func (d *Document) MustExist(name string) Layer {
} }
return set return set
} }
// Save saves the Document in place.
func (d *Document) Save() error {
js := fmt.Sprintf("var d=app.open(File('%s'));\nd.save();", d.FullName())
if _, err := DoJS("compilejs", js); err != nil {
return err
}
return nil
}

106
document_test.go Normal file
View File

@@ -0,0 +1,106 @@
package ps
import (
"log"
"os"
"path/filepath"
"reflect"
"runtime"
"testing"
)
// wd is the working directory
var wd string
func init() {
_, file, _, ok := runtime.Caller(0)
if !ok {
log.Fatal("runtime.Caller(0) returned !ok")
}
wd = filepath.Dir(file)
f, err := os.Create("test.log")
if err != nil {
log.Fatal(err)
}
log.SetOutput(f)
}
func TestDocument_Dump(t *testing.T) {
// Must be true for test to be valid.
Mode = Normal
tests := []struct {
name string
}{
{"Test"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Get rid of old Dump.
os.Remove(filepath.Join(wd, tt.name+".json"))
// Generate a fresh Doc (loaded slowly).
want, err := Open(filepath.Join(wd, tt.name+".psd"))
if err != nil {
t.Fatal(err)
}
// Dump the contents.
want.Dump()
// Grab a new version of the doc (loaded from json).
got, err := Open(filepath.Join(wd, tt.name+".psd"))
if err != nil {
t.Fatal(err)
}
got.layerSets[0].current = true
if !reflect.DeepEqual(got, want) {
t.Errorf("wanted: %+v\ngot: %+v", want, got)
}
})
}
}
func TestDocument_Save(t *testing.T) {
file := filepath.Join(wd, "Test.psd")
d, err := Open(file)
if err != nil {
t.Fatal(err)
}
layerName := "Group 1"
lyr := d.LayerSet(layerName)
if lyr == nil {
t.Fatalf("LayerSet '%s' was not found", layerName)
}
// Change a layer name.
_, err = DoJS(filepath.Join("SetName"), JSLayer(lyr.Path()), "Group 2")
if err != nil {
t.Error(err)
}
defer func() {
if err := DoAction("DK", "Undo"); err != nil {
t.Error(err)
}
err := d.Save()
if err != nil {
t.Fatal(err)
}
}()
err = d.Save()
if err != nil {
t.Fatal(err)
}
d2, err := Open(file)
if err != nil {
t.Fatal(err)
}
if reflect.DeepEqual(d, d2) {
t.Errorf("wanted: %+v\ngot: %+v", d, d2)
}
}

View File

@@ -6,5 +6,5 @@ func ExampleJSLayer() {
// The path of a layer inside a top level group. // The path of a layer inside a top level group.
path := "Group 1/Layer 1" path := "Group 1/Layer 1"
fmt.Println(JSLayer(path)) fmt.Println(JSLayer(path))
// Output: app.activeDocument.layerSets.getByName('Group 1').artLayers.getByName('Layer 1'); // Output: app.activeDocument.layerSets.getByName('Group 1').artLayers.getByName('Layer 1')
} }

View File

@@ -201,8 +201,7 @@ func (l *LayerSet) SetVisible(b bool) error {
if l.visible == b { if l.visible == b {
return nil return nil
} }
js := fmt.Sprintf("%s.visible=%v;", strings.TrimRight( js := fmt.Sprintf("%s.visible=%v;", JSLayer(l.Path()), b)
JSLayer(l.Path()), ";"), b)
if _, err := DoJS("compilejs.jsx", js); err != nil { if _, err := DoJS("compilejs.jsx", js); err != nil {
return err return err
} }
@@ -297,10 +296,3 @@ func (l *LayerSet) Refresh() error {
l.current = true l.current = true
return nil return nil
} }
func (l *LayerSet) Set(ll *LayerSet) {
if ll == nil {
panic("AHHHHHH")
}
l = ll
}

28
ps.go
View File

@@ -16,11 +16,11 @@ import (
) )
// The full path to this directory. // The full path to this directory.
var pkgpath string var pkgPath string
func init() { func init() {
_, file, _, _ := runtime.Caller(0) _, file, _, _ := runtime.Caller(0)
pkgpath = filepath.Dir(file) pkgPath = filepath.Dir(file)
} }
// ApplyDataset fills out a template file with information // ApplyDataset fills out a template file with information
@@ -40,9 +40,9 @@ func Close(save SaveOption) error {
return err return err
} }
// DoAction runs the Photoshop Action with the given name from the Action Set "from". // DoAction runs the Photoshop Action with name 'action' from ActionSet 'set'.
func DoAction(action, from string) error { func DoAction(set, action string) error {
_, err := runner.Run("action", action, from) _, err := runner.Run("action", set, action)
return err return err
} }
@@ -72,8 +72,10 @@ func DoJS(path string, args ...string) ([]byte, error) {
args = append([]string{outpath.Name()}, args...) args = append([]string{outpath.Name()}, args...)
// If passed a script by name, assume it's in the default folder. // If passed a script by name, assume it's in the default folder.
if filepath.Dir(path) == "." { scripts := filepath.Join(pkgPath, "runner", "scripts")
path = filepath.Join(pkgpath, "runner", "scripts", path) b, err := filepath.Match(scripts, path)
if !b || err != nil {
path = filepath.Join(scripts, path)
} }
args = append([]string{path}, args...) args = append([]string{path}, args...)
@@ -99,8 +101,6 @@ func Init() error {
// JSLayer "compiles" Javascript code to get an ArtLayer with the given path. // JSLayer "compiles" Javascript code to get an ArtLayer with the given path.
// The output always ends with a semicolon, so if you want to access a specific // The output always ends with a semicolon, so if you want to access a specific
// property of the layer, you'll have to trim the output before concatenating. // property of the layer, you'll have to trim the output before concatenating.
//
// TODO(sbrow): get rid of the semicolon at the end of JSLayer.
func JSLayer(path string) string { func JSLayer(path string) string {
pth := strings.Split(path, "/") pth := strings.Split(path, "/")
js := "app.activeDocument" js := "app.activeDocument"
@@ -113,7 +113,7 @@ func JSLayer(path string) string {
if pth[last] != "" { if pth[last] != "" {
js += fmt.Sprintf(".artLayers.getByName('%s')", pth[last]) js += fmt.Sprintf(".artLayers.getByName('%s')", pth[last])
} }
return js + ";" return js
} }
// JSLayerMerge gets the Javascript code to get the Layer or LayerSet with this path // JSLayerMerge gets the Javascript code to get the Layer or LayerSet with this path
@@ -129,9 +129,11 @@ func JSLayerMerge(path string) string {
// Open opens a Photoshop document with the specified path. // Open opens a Photoshop document with the specified path.
// If Photoshop is not currently running, it is started before // If Photoshop is not currently running, it is started before
// opening the document. // opening the document.
func Open(path string) error { func Open(path string) (*Document, error) {
_, err := runner.Run("open", path) if _, err := runner.Run("open", path); err != nil {
return err return nil, err
}
return ActiveDocument()
} }
// Quit exits Photoshop, closing all open documents using the given save option. // Quit exits Photoshop, closing all open documents using the given save option.

View File

@@ -51,7 +51,10 @@ func Run(name string, args ...string) ([]byte, error) {
cmd := exec.Command(std.Cmd, parseArgs(name, args...)...) cmd := exec.Command(std.Cmd, parseArgs(name, args...)...)
cmd.Stdout, cmd.Stderr = &out, &errs cmd.Stdout, cmd.Stderr = &out, &errs
if err := cmd.Run(); err != nil || len(errs.Bytes()) != 0 { if err := cmd.Run(); err != nil || len(errs.Bytes()) != 0 {
return out.Bytes(), fmt.Errorf("err: \"%s %s\"\nargs: \"%s\"\nout: \"%s\"", err, errs.String(), args, out.String()) return out.Bytes(), fmt.Errorf(`err: "%s"
errs.String(): "%s"
args: "%s"
out: "%s"`, err, errs.String(), args, out.String())
} }
return out.Bytes(), nil return out.Bytes(), nil
} }

View File

@@ -0,0 +1,5 @@
#include lib.js
var stdout=newFile(arguments[0]);
var obj=eval(arguments[1]);
obj.name=arguments[2];
stdout.close();

View File

@@ -1,5 +1,6 @@
' Runs an action with the given name (Argument 1) from the given set (Argument 0).
set appRef = CreateObject("Photoshop.Application") set appRef = CreateObject("Photoshop.Application")
' No dialogs' ' No dialogs.
dlgMode = 3 dlgMode = 3
set desc = CreateObject( "Photoshop.ActionDescriptor" ) set desc = CreateObject( "Photoshop.ActionDescriptor" )

View File

@@ -4,8 +4,6 @@ Set appRef = CreateObject("Photoshop.Application")
if wScript.Arguments.Count = 0 then if wScript.Arguments.Count = 0 then
wScript.Echo "Missing parameters" wScript.Echo "Missing parameters"
else else
' wScript.Echo wScript.Arguments(0)
' wScript.Echo wScript.Arguments(1)
path = wScript.Arguments(0) path = wScript.Arguments(0)
args = wScript.Arguments(1) args = wScript.Arguments(1)
error = appRef.DoJavaScriptFile(path, Split(args, ",,")) error = appRef.DoJavaScriptFile(path, Split(args, ",,"))

View File

@@ -1,7 +1,7 @@
#include lib.js #include lib.js
var stdout = newFile(arguments[0]); var stdout = newFile(arguments[0]);
var doc = app.activeDocument; var doc = app.activeDocument;
stdout.writeln(('{"Name": "'+doc.name+'", "Height":'+doc.height+ stdout.writeln(('{"Name": "'+doc.name+'", "FullName": "'+doc.fullName+'", "Height":'+doc.height+
', "Width":'+doc.width+', "ArtLayers": [').replace(/ px/g, "")); ', "Width":'+doc.width+', "ArtLayers": [').replace(/ px/g, ""));
stdout.writeln(layers(doc.artLayers)) stdout.writeln(layers(doc.artLayers))

View File

@@ -4,7 +4,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
"strings"
) )
// TextItem holds the text element of a TextLayer. // TextItem holds the text element of a TextLayer.
@@ -62,7 +61,7 @@ func (t *TextItem) SetText(txt string) {
return return
} }
var err error var err error
lyr := strings.TrimRight(JSLayer(t.parent.Path()), ";") lyr := JSLayer(t.parent.Path())
bndtext := "[[' + lyr.bounds[0] + ',' + lyr.bounds[1] + '],[' + lyr.bounds[2] + ',' + lyr.bounds[3] + ']]" bndtext := "[[' + lyr.bounds[0] + ',' + lyr.bounds[1] + '],[' + lyr.bounds[2] + ',' + lyr.bounds[3] + ']]"
js := fmt.Sprintf(`%s.textItem.contents='%s';var lyr = %[1]s;stdout.writeln(('%[3]s').replace(/ px/g, ''));`, js := fmt.Sprintf(`%s.textItem.contents='%s';var lyr = %[1]s;stdout.writeln(('%[3]s').replace(/ px/g, ''));`,
lyr, txt, bndtext) lyr, txt, bndtext)
@@ -87,7 +86,7 @@ func (t *TextItem) SetSize(s float64) {
if t.size == s { if t.size == s {
return return
} }
lyr := strings.TrimRight(JSLayer(t.parent.Path()), ";") lyr := JSLayer(t.parent.Path())
js := fmt.Sprintf("%s.textItem.size=%f;", lyr, s) js := fmt.Sprintf("%s.textItem.size=%f;", lyr, s)
_, err := DoJS("compilejs.jsx", js) _, err := DoJS("compilejs.jsx", js)
if err != nil { if err != nil {