Repository: score-spec/score-compose (go)

Issue:
[FEATURE] support volume subpath
Documentation says:

> Volume mounts with path will be rejected. Docker compose doesn't support sub-path mounts for Docker volumes."

this isn't true (since https://github.com/compose-spec/compose-go/pull/594)
```yaml
      - type: volume
        source: foo
        target: /app
        volume:
          subpath: etc/settings
```

Pull request description:
fix: support subpath on docker or bind volumes
This fixes #166 which correctly raised the issue that we blanket disallow volume subpath's but in reality docker is more nuanced and does support sub path volumes for both docker volumes and can be simulated in bind volumes by modifying the bind path.

For tmpfs we still can't really support this however but users can replace tmpfs with a docker volume and get approximately the same utility. This depends on the outputs of the provisioner which indicate the docker volume type.


Patch:
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index 87323c6..b9447cc 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -1,126 +1,4 @@
-# Contributor Covenant Code of Conduct
+# Code of Conduct
 
-## Our Pledge
+For more information about our code of conduct, please visit [this page](https://github.com/score-spec/spec/blob/main/CODE_OF_CONDUCT.md).
 
-We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of gender identity and expression, sexual orientation, disability, physical appearance, body size, citizenship, nationality, ethnic or social origin, pregnancy, familial status, veteran status, genetic information, religion or belief (or lack thereof), membership of a national minority, property, age, education, socio-economic status, technical choices, and experience level.
-
-We pledge to act and interact in ways that contribute to an open, welcoming,
-diverse, inclusive, and healthy community.
-
-We do not tolerate harassment by and/or of members of our community in any form.
-
-## Our Standards
-
-Examples of behavior that contributes to a positive environment for our
-community include:
-
-- Demonstrating empathy and kindness toward other people
-- Being respectful of differing opinions, viewpoints, and experiences
-- Giving and gracefully accepting constructive feedback
-- Accepting responsibility and apologizing to those affected by our mistakes,
-  and learning from the experience
-- Focusing on what is best not just for us as individuals, but for the overall
-  community
-- Giving everyone an opportunity to be heard
-- Using welcoming and inclusive language
-
-Examples of unacceptable behavior include:
-
-- The use of sexualized language or imagery, and sexual attention or advances of
-  any kind
-- Trolling, insulting or derogatory remarks, and personal or political attacks
-- Public or private harassment
-- Publishing others' private information, such as a physical or email address,
-  without their explicit permission
-- Other conduct which could reasonably be considered inappropriate in a
-  professional setting
-
-## Enforcement Responsibilities
-
-Community leaders are responsible for clarifying and enforcing our standards of
-acceptable behavior and will take appropriate and fair corrective action in
-response to any behavior that they deem inappropriate, threatening, offensive,
-or harmful.
-
-Community leaders have the right and responsibility to remove, edit, or reject
-comments, commits, code, wiki edits, issues, and other contributions that are
-not aligned to this Code of Conduct, and will communicate reasons for moderation
-decisions when appropriate.
-
-## Scope
-
-This Code of Conduct applies within all community spaces, and also applies when
-an individual is officially representing the community in public spaces.
-Examples of representing our community include using an official e-mail address,
-posting via an official social media account, or acting as an appointed
-representative at an online or offline event.
-
-## Enforcement
-
-Instances of abusive, harassing, or otherwise unacceptable behavior may be
-reported to the community leaders responsible for enforcement at abuse@score.dev.
-
-All complaints will be reviewed and investigated promptly and fairly.
-
-All community leaders are obligated to respect the privacy and security of the
-reporter of any incident.
-
-## Enforcement Guidelines
-
-Community leaders will follow these Community Impact Guidelines in determining
-the consequences for any action they deem in violation of this Code of Conduct:
-
-### 1. Correction
-
-**Community Impact**: Use of inappropriate language or other behavior deemed
-unprofessional or unwelcome in the community.
-
-**Consequence**: A private, written warning from community leaders, providing
-clarity around the nature of the violation and an explanation of why the
-behavior was inappropriate. A public apology may be requested.
-
-### 2. Warning
-
-**Community Impact**: A violation through a single incident or series of
-actions.
-
-**Consequence**: A warning with consequences for continued behavior. No
-interaction with the people involved, including unsolicited interaction with
-those enforcing the Code of Conduct, for a specified period of time. This
-includes avoiding interactions in community spaces as well as external channels
-like social media. Violating these terms may lead to a temporary or permanent
-ban.
-
-### 3. Temporary Ban
-
-**Community Impact**: A serious violation of community standards, including
-sustained inappropriate behavior.
-
-**Consequence**: A temporary ban from any sort of interaction or public
-communication with the community for a specified period of time. No public or
-private interaction with the people involved, including unsolicited interaction
-with those enforcing the Code of Conduct, is allowed during this period.
-Violating these terms may lead to a permanent ban.
-
-### 4. Permanent Ban
-
-**Community Impact**: Demonstrating a pattern of violation of community
-standards, including sustained inappropriate behavior, harassment of an
-individual, or aggression toward or disparagement of classes of individuals.
-
-**Consequence**: A permanent ban from any sort of public interaction within the
-community.
-
-## Attribution
-
-This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
-
-Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
-
-For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
-
-[homepage]: https://www.contributor-covenant.org
-[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
-[Mozilla CoC]: https://github.com/mozilla/diversity
-[FAQ]: https://www.contributor-covenant.org/faq
-[translations]: https://www.contributor-covenant.org/translations
diff --git a/README.md b/README.md
index bb897ff..46015b0 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,6 @@
 |---------------------------------------------------------------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
 | `containers.*.resources.limits` / `containers.*.resources.requests` | none    | **Limits will be validated but ignored.** While the compose specification has some support for this, it is requires particular Docker versions that cannot be relied on. *This should have no impact on Workload execution*.                                                                                                                        |
 | `containers.*.livenessProbe` / `containers.*.readinessProbe`        | none    | **Probes will be validated but ignored.** The Score specification only details K8s-like HTTP probes, but the compose specification only supports direct command execution. We cannot convert between the two reliably. *This should have no impact on Workload execution*. Tracked in [#86](https://github.com/score-spec/score-compose/issues/86). |
-| `containers.*.volumes[*].path`                                      | none    | **Volume mounts with `path` will be rejected.** Docker compose doesn't support sub-path mounts for Docker volumes.                                                                                                                                                                                                                                  |
 
 ## Resource support
 
diff --git a/internal/command/default.provisioners.yaml b/internal/command/default.provisioners.yaml
index 51631b4..0aa1121 100644
--- a/internal/command/default.provisioners.yaml
+++ b/internal/command/default.provisioners.yaml
@@ -163,7 +163,7 @@
         test: ["CMD", "pg_isready", "-U", "postgres"]
         interval: 2s
         timeout: 2s
-        retries: 10
+        retries: 15
     {{ dig .Init.sk "instanceServiceName" "" .Shared }}-init:
       image: postgres:16-alpine
       entrypoint: ["/bin/sh"]
@@ -254,7 +254,7 @@
         test: ["CMD-SHELL", "mc alias set myminio http://localhost:9000 {{ dig .Init.sk "instanceUsername" "" .Shared }} {{ dig .Init.sk "instancePassword" "" .Shared }}"]
         interval: 2s
         timeout: 2s
-        retries: 10
+        retries: 15
       environment:
         MINIO_ROOT_USER: {{ dig .Init.sk "instanceUsername" "" .Shared | quote }}
         MINIO_ROOT_PASSWORD: {{ dig .Init.sk "instancePassword" "" .Shared | quote }}
@@ -341,7 +341,7 @@
         test: ["CMD-SHELL", "rabbitmq-diagnostics -q check_port_connectivity"]
         interval: 2s
         timeout: 5s
-        retries: 5
+        retries: 15
     {{ dig .Init.sk "instanceServiceName" "" .Shared }}-init:
       image: rabbitmq:3-management-alpine
       entrypoint: ["/bin/sh"]
@@ -519,7 +519,7 @@
         test: ["CMD-SHELL", "echo 'db.runCommand(\"ping\").ok' | mongosh -u $$MONGO_INITDB_ROOT_USERNAME -p $$MONGO_INITDB_ROOT_PASSWORD"]
         interval: 2s
         timeout: 5s
-        retries: 5
+        retries: 15
         start_period: 10s
       volumes:
       - type: volume
diff --git a/internal/compose/convert.go b/internal/compose/convert.go
index 71128e7..9748043 100644
--- a/internal/compose/convert.go
+++ b/internal/compose/convert.go
@@ -95,13 +95,9 @@ func ConvertSpec(state *project.State, spec *score.Workload) (*compose.Project,
 		if len(cSpec.Volumes) > 0 {
 			volumes = make([]compose.ServiceVolumeConfig, len(cSpec.Volumes))
 			for idx, vol := range cSpec.Volumes {
-				if vol.Path != nil && *vol.Path != "" {
-					return nil, fmt.Errorf("containers.%s.volumes[%d].path: can't mount named volume with sub path '%s': not supported", containerName, idx, *vol.Path)
-				}
-
 				cfg, err := convertVolumeSourceIntoVolume(state, deferredSubstitutionFunction, workloadName, vol)
 				if err != nil {
-					return nil, fmt.Errorf("containers.%s.volumes[%d].source: %w", containerName, idx, err)
+					return nil, fmt.Errorf("containers.%s.volumes[%d]: %w", containerName, idx, err)
 				}
 				volumes[idx] = *cfg
 			}
@@ -293,6 +289,7 @@ func convertVolumeSourceIntoVolume(state *project.State, substitutionFunction fu
 	}
 
 	// now if the resolves source is a volume we can check the outputs or throw an error
+
 	res, ok := state.Resources[framework.ResourceUid(resolvedVolumeSource)]
 	if ok {
 		volType, ok := res.Outputs["type"].(string)
@@ -315,6 +312,12 @@ func convertVolumeSourceIntoVolume(state *project.State, substitutionFunction fu
 			}
 			outputVolume.Source = s.Source
 			outputVolume.Volume = s.Volume
+			if vol.Path != nil && *vol.Path != "" {
+				if outputVolume.Volume == nil {
+					outputVolume.Volume = &compose.ServiceVolumeVolume{}
+				}
+				outputVolume.Volume.Subpath = filepath.Join(outputVolume.Volume.Subpath, *vol.Path)
+			}
 		case "tmpfs":
 			s := struct {
 				Type  string                      `json:"type"`
@@ -324,6 +327,9 @@ func convertVolumeSourceIntoVolume(state *project.State, substitutionFunction fu
 				return nil, fmt.Errorf("resource '%s' outputs cannot decode for tmpfs: %w", resolvedVolumeSource, err)
 			}
 			outputVolume.Tmpfs = s.Tmpfs
+			if vol.Path != nil && *vol.Path != "" {
+				return nil, fmt.Errorf("can't mount named tmpfs volume with sub path '%s': not supported", *vol.Path)
+			}
 		case "bind":
 			s := struct {
 				Type   string                     `json:"type"`
@@ -334,6 +340,9 @@ func convertVolumeSourceIntoVolume(state *project.State, substitutionFunction fu
 				return nil, fmt.Errorf("resource '%s' outputs cannot decode for bind: %w", resolvedVolumeSource, err)
 			}
 			outputVolume.Source = s.Source
+			if vol.Path != nil && *vol.Path != "" {
+				outputVolume.Source = filepath.Join(outputVolume.Source, *vol.Path)
+			}
 			outputVolume.Bind = s.Bind
 		default:
 			return nil, fmt.Errorf("resource '%s' has invalid type '%s'", resolvedVolumeSource, volType)


Test patch:
diff --git a/internal/command/generate_test.go b/internal/command/generate_test.go
index 51a6e80..87a579f 100644
--- a/internal/command/generate_test.go
+++ b/internal/command/generate_test.go
@@ -1030,6 +1030,11 @@ func TestInitAndGenerate_with_volume_types(t *testing.T) {
 
 	// write custom providers
 	assert.NoError(t, os.WriteFile(filepath.Join(td, ".score-compose", "00-custom.provisioners.yaml"), []byte(`
+- uri: template://docker-volume
+  type: volume
+  outputs: |
+    type: volume
+    source: named-volume
 - uri: template://tmpfs-volume
   type: tmp-volume
   outputs: |
@@ -1058,11 +1063,17 @@ containers:
       source: ${resources.v1}
     - target: /mnt/v2
       source: ${resources.v2}
+      path: thing
+    - target: /mnt/v3
+      source: ${resources.v3}
+      path: other/thing
 resources:
   v1:
     type: tmp-volume
   v2:
     type: bind-volume
+  v3:
+    type: volume
 `), 0644))
 
 	// generate
@@ -1080,10 +1091,15 @@ services:
         image: busybox
         volumes:
             - type: bind
-              source: /dev/something
+              source: /dev/something/thing
               target: /mnt/v2
               bind:
                 create_host_path: true
+            - type: volume
+              source: named-volume
+              target: /mnt/v3
+              volume:
+                subpath: other/thing
             - type: tmpfs
               source: tmp-volume.default#example.v1
               target: /mnt/v1
diff --git a/internal/command/run_test.go b/internal/command/run_test.go
index c00c20a..899342d 100644
--- a/internal/command/run_test.go
+++ b/internal/command/run_test.go
@@ -251,26 +251,6 @@ func TestExample_invalid_spec(t *testing.T) {
 	assert.NotEqual(t, "", strings.TrimSpace(stderr))
 }
 
-func TestVolumeSubPathNotSupported(t *testing.T) {
-	td := t.TempDir()
-	assert.NoError(t, os.WriteFile(filepath.Join(td, "score.yaml"), []byte(`
-apiVersion: score.dev/v1b1
-metadata:
-  name: example-workload-name123
-containers:
-  container-one1:
-    image: localhost:4000/repo/my-image:tag
-    volumes:
-    - source: volume-name
-      target: /mnt/something
-      path: /sub/path
-`), 0600))
-	stdout, stderr, err := executeAndResetCommand(context.Background(), rootCmd, []string{"run", "--file", filepath.Join(td, "score.yaml"), "--output", filepath.Join(td, "compose.yaml")})
-	assert.EqualError(t, err, "building docker-compose configuration: containers.container-one1.volumes[0].path: can't mount named volume with sub path '/sub/path': not supported")
-	assert.Equal(t, "", stdout)
-	assert.NotEqual(t, "", strings.TrimSpace(stderr))
-}
-
 func TestFilesNotSupported(t *testing.T) {
 	td := t.TempDir()
 	assert.NoError(t, os.WriteFile(filepath.Join(td, "score.yaml"), []byte(`
diff --git a/internal/compose/convert_test.go b/internal/compose/convert_test.go
index 6158526..5739927 100644
--- a/internal/compose/convert_test.go
+++ b/internal/compose/convert_test.go
@@ -123,7 +123,7 @@ func TestScoreConvert(t *testing.T) {
 						},
 						Volumes: []score.ContainerVolumesElem{
 							{
-								Source:   "data",
+								Source:   "${resources.data}",
 								Target:   "/mnt/data",
 								ReadOnly: util.Ref(true),
 							},
@@ -135,7 +135,7 @@ func TestScoreConvert(t *testing.T) {
 						Type: "environment",
 					},
 					"app-db": {
-						Type: "postgress",
+						Type: "mysql",
 					},
 					"some-dns": {
 						Type: "dns",
@@ -163,7 +163,7 @@ func TestScoreConvert(t *testing.T) {
 						Volumes: []compose.ServiceVolumeConfig{
 							{
 								Type:     "volume",
-								Source:   "data",
+								Source:   "example",
 								Target:   "/mnt/data",
 								ReadOnly: true,
 							},
@@ -196,7 +196,7 @@ func TestScoreConvert(t *testing.T) {
 						},
 						Volumes: []score.ContainerVolumesElem{
 							{
-								Source:   "data",
+								Source:   "${resources.data}",
 								Target:   "/mnt/data",
 								ReadOnly: util.Ref(true),
 							},
@@ -236,7 +236,7 @@ func TestScoreConvert(t *testing.T) {
 						Volumes: []compose.ServiceVolumeConfig{
 							{
 								Type:     "volume",
-								Source:   "data",
+								Source:   "example",
 								Target:   "/mnt/data",
 								ReadOnly: true,
 							},
@@ -354,10 +354,8 @@ func TestScoreConvert(t *testing.T) {
 			},
 		},
 
-		// Errors handling
-		//
 		{
-			Name: "Should report an error for volumes with sub path (not supported)",
+			Name: "Volume with sub-path should succeed",
 			Source: &score.Workload{
 				Metadata: score.WorkloadMetadata{
 					"name": "test",
@@ -367,7 +365,7 @@ func TestScoreConvert(t *testing.T) {
 						Image: "busybox",
 						Volumes: []score.ContainerVolumesElem{
 							{
-								Source:   "data",
+								Source:   "${resources.data}",
 								Target:   "/mnt/data",
 								Path:     util.Ref("sub/path"),
 								ReadOnly: util.Ref(true),
@@ -381,9 +379,34 @@ func TestScoreConvert(t *testing.T) {
 					},
 				},
 			},
-			Error: errors.New("not supported"),
+			Project: &compose.Project{
+				Services: compose.Services{
+					"test-backend": {
+						Name: "test-backend",
+						Annotations: map[string]string{
+							"compose.score.dev/workload-name": "test",
+						},
+						Image:       "busybox",
+						Hostname:    "test",
+						Environment: compose.MappingWithEquals{},
+						Volumes: []compose.ServiceVolumeConfig{
+							{
+								Type:     "volume",
+								Source:   "example",
+								Target:   "/mnt/data",
+								ReadOnly: true,
+								Volume: &compose.ServiceVolumeVolume{
+									Subpath: "sub/path",
+								},
+							},
+						},
+					},
+				},
+			},
 		},
 
+		// Errors handling
+		//
 		{
 			Name: "Should report an error for volume that doesn't exist in resources",
 			Source: &score.Workload{
@@ -395,7 +418,7 @@ func TestScoreConvert(t *testing.T) {
 					},
 				},
 			},
-			Error: errors.New("containers.test.volumes[0].source: resource 'data' does not exist"),
+			Error: errors.New("containers.test.volumes[0]: resource 'data' does not exist"),
 		},
 
 		{
@@ -410,7 +433,7 @@ func TestScoreConvert(t *testing.T) {
 				},
 				Resources: map[string]score.Resource{"data": {Type: "thing"}},
 			},
-			Error: errors.New("containers.test.volumes[0].source: resource 'data' does not exist"),
+			Error: errors.New("containers.test.volumes[0]: resource 'thing.default#test.data' has no 'type' output"),
 		},
 	}
 
@@ -418,21 +441,22 @@ func TestScoreConvert(t *testing.T) {
 		t.Run(tt.Name, func(t *testing.T) {
 
 			state := &project.State{
-				Workloads: map[string]framework.ScoreWorkloadState[project.WorkloadExtras]{
-					"test": {Spec: score.Workload{Resources: map[string]score.Resource{
-						"env":      {Type: "environment"},
-						"app-db":   {Type: "thing"},
-						"some-dns": {Type: "thing"},
-					}}},
-				},
+				Workloads: map[string]framework.ScoreWorkloadState[project.WorkloadExtras]{},
 				Resources: map[framework.ResourceUid]framework.ScoreResourceState[framework.NoExtras]{},
 			}
+			state, _ = state.WithWorkload(tt.Source, nil, project.WorkloadExtras{})
+			state, _ = state.WithPrimedResources()
+
 			evt := new(envprov.Provisioner)
 			state.Resources["environment.default#test.env"] = framework.ScoreResourceState[framework.NoExtras]{OutputLookupFunc: evt.LookupOutput}
 			po, _ := evt.GenerateSubProvisioner("app-db", "").Provision(nil, nil)
-			state.Resources["thing.default#test.app-db"] = framework.ScoreResourceState[framework.NoExtras]{OutputLookupFunc: po.OutputLookupFunc}
+			state.Resources["mysql.default#test.app-db"] = framework.ScoreResourceState[framework.NoExtras]{OutputLookupFunc: po.OutputLookupFunc}
 			po, _ = evt.GenerateSubProvisioner("some-dns", "").Provision(nil, nil)
-			state.Resources["thing.default#test.some-dns"] = framework.ScoreResourceState[framework.NoExtras]{OutputLookupFunc: po.OutputLookupFunc}
+			state.Resources["dns.default#test.some-dns"] = framework.ScoreResourceState[framework.NoExtras]{OutputLookupFunc: po.OutputLookupFunc}
+			state.Resources["volume.default#test.data"] = framework.ScoreResourceState[framework.NoExtras]{Outputs: map[string]interface{}{
+				"type":   "volume",
+				"source": "example",
+			}}
 
 			proj, err := ConvertSpec(state, tt.Source)